{
  "repo": "tidbcloud/auth-server",
  "binary": "auth-server",
  "binary_path": "cmd/auth-server/main.go",
  "dependencies": {
    "AuthServerCobra.Execute": {
      "infrastructure": {},
      "services": []
    },
    "AuthServerCobra.LoadConfig": {
      "infrastructure": {
        "filesystem": {
          "conditions": [
            "Always"
          ],
          "operations": [
            {
              "operation": "READ FILE",
              "trigger": "Load the local YAML config file selected by the persistent --config flag before any mode-specific startup runs",
              "conditions": [
                "config.InitConfig(configPath) is reached from rootCmd.PersistentPreRunE"
              ],
              "implementation": "config.InitConfig(path) -> viper.SetConfigFile(path); viper.ReadInConfig()"
            }
          ]
        }
      },
      "services": [
        {
          "name": "config-service-oneconfig",
          "target_repo": "tidbcloud/config-service",
          "target_interface": "oneconfig remote provider",
          "operation_type": "config_remote_read",
          "conditions": [
            "Always after local config load succeeds"
          ],
          "operations": [
            {
              "operation": "LOAD REMOTE CONFIG",
              "trigger": "Merge oneconfig-account/config.yaml into the global Viper state",
              "conditions": [
                "viper.ReadInConfig() succeeded"
              ],
              "implementation": "config.LoadRemoteConfig(context.Background()) -> viper.AddRemoteProvider(..., \"oneconfig-account/config.yaml\"); viper.ReadRemoteConfig()"
            }
          ]
        }
      ]
    },
    "AuthServerCobra.WatchRemoteConfig": {
      "infrastructure": {},
      "services": [
        {
          "name": "config-service-oneconfig",
          "target_repo": "tidbcloud/config-service",
          "target_interface": "oneconfig remote provider",
          "operation_type": "config_remote_watch",
          "conditions": [
            "Only after LoadRemoteConfig succeeded"
          ],
          "operations": [
            {
              "operation": "START WATCHER",
              "trigger": "Launch the background one-minute polling loop that refreshes Viper remote config state",
              "conditions": [
                "config.LoadRemoteConfig(...) returned nil"
              ],
              "implementation": "config.LoadRemoteConfig(...) -> go watchViperConfig(ctx)"
            },
            {
              "operation": "WATCH REMOTE CONFIG",
              "trigger": "Refresh remote config state on every watch loop iteration",
              "conditions": [
                "watchViperConfig goroutine is running"
              ],
              "implementation": "watchViperConfig(ctx) -> time.Sleep(time.Minute); viper.WatchRemoteConfig()"
            }
          ]
        }
      ]
    },
    "AuthServerHTTPLifecycle.Startup": {
      "infrastructure": {},
      "services": []
    },
    "AuthServerHTTPLifecycle.InitializeTracing": {
      "infrastructure": {},
      "services": []
    },
    "AuthServerHTTPLifecycle.InitializeLoggerAndSentry": {
      "infrastructure": {},
      "services": []
    },
    "AuthServerHTTPLifecycle.InitializeDatabase": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Always in http mode"
          ],
          "operations": [
            {
              "operation": "OPEN DB HANDLE",
              "trigger": "Connect to MySQL using DB_PASSWORD plus MysqlConfig from the loaded config",
              "conditions": [
                "os.Getenv(\"DB_PASSWORD\") != \"\""
              ],
              "implementation": "database.Connect(ctx, centralConfig) -> gorm.Open(mysql.Open(url), &gorm.Config{TablePrefix: \"auth_server_\"})"
            }
          ]
        }
      },
      "services": []
    },
    "AuthServerHTTPLifecycle.InitializeContainer": {
      "infrastructure": {},
      "services": [
        {
          "name": "account-provider-grpc",
          "target_repo": "tidbcloud/account",
          "target_interface": "AccountAPIService",
          "operation_type": "grpc_connect",
          "conditions": [
            "Always in http mode"
          ],
          "operations": [
            {
              "operation": "CONNECT",
              "trigger": "Initialize the shared AccountAPIService client used by auth middleware and OAuth2 services",
              "conditions": [
                "container.InitGlobalContainer(database.DBConn.DB) is reached"
              ],
              "implementation": "container.initExternalService() -> grpc.GetAccountProviderSvcClient() -> tigrpc.NewClientConn(config.Global().GrpcConfig.AccountProviderSvcAddr, tigrpc.WithDefault())"
            }
          ]
        }
      ]
    },
    "AuthServerHTTPLifecycle.StartMetricsServer": {
      "infrastructure": {},
      "services": []
    },
    "AuthServerHTTPLifecycle.StartHTTPServer": {
      "infrastructure": {},
      "services": []
    },
    "HTTP GET /metrics": {
      "infrastructure": {},
      "services": []
    },
    "HTTP GET /healthz": {
      "infrastructure": {},
      "services": []
    },
    "HTTP GET /swagger/*any": {
      "infrastructure": {
        "filesystem": {
          "conditions": [
            "Swagger assets and generated docs are available in the binary build"
          ],
          "operations": [
            {
              "operation": "READ DOC ASSETS",
              "trigger": "Serve the Swagger UI and generated OAuth2 API docs",
              "conditions": [
                "GET /swagger/*any is reached"
              ],
              "implementation": "ginSwagger.WrapHandler(swaggerfiles.Handler) with docs/oauth2 side-effect import"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /v1/device_authorization": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after request binding and request validation succeed"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "trigger": "Load the OAuth2 application by client_id and verify that it is a device-code app",
              "conditions": [
                "req.Validate() returned nil"
              ],
              "implementation": "oauth2Svc.HandleDeviceAuthorizationRequest(...) -> repository.GetOauth2ApplicationByClientID(ctx, db, clientID)"
            },
            {
              "operation": "INSERT",
              "trigger": "Create the pending device grant row with generated user_code and encrypted device_code",
              "conditions": [
                "application exists",
                "app.GrantType == entity.Oauth2DeviceCode"
              ],
              "implementation": "createDeviceGrantWithRetry(...) -> repository.CreateOauth2DeviceGrant(ctx, db, obj)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /v1/token": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Binding and top-level token request validation succeeded; downstream DB branches depend on grant_type"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "trigger": "Load the OAuth2 application by client_id for all supported grant types",
              "conditions": [
                "req.Validate() returned nil",
                "grant_type is device_code, authorization_code, or refresh_token"
              ],
              "implementation": "HandleDeviceTokenRequest / CreateAccessTokenByCodeGrant / HandleRefreshTokenRequest -> repository.GetOauth2ApplicationByClientID(ctx, db, clientID)"
            },
            {
              "operation": "SELECT",
              "trigger": "Lock and inspect the device grant while polling with a device_code grant",
              "conditions": [
                "req.GrantType == oauth2_svc.DeviceCodeGrantType",
                "req.ValidateDeviceGrant() returned nil"
              ],
              "implementation": "HandleDeviceTokenRequest(...) -> repository.GetOauth2DeviceGrantByDeviceCodeWithLock(ctx, tx, encryptedDeviceCode)"
            },
            {
              "operation": "UPDATE",
              "trigger": "Update LastPolledAt when a device grant is still pending and the caller is not polling too quickly",
              "conditions": [
                "req.GrantType == oauth2_svc.DeviceCodeGrantType",
                "grant.Status == entity.Oauth2GrantStatusPending",
                "grant.LastPolledAt is nil or now >= nextPollTime"
              ],
              "implementation": "repository.UpdateOauth2DeviceGrant(... LastPolledAt ...)"
            },
            {
              "operation": "UPDATE",
              "trigger": "Mark a device grant revoked after an approved device grant is exchanged for an access token",
              "conditions": [
                "req.GrantType == oauth2_svc.DeviceCodeGrantType",
                "grant.Status == entity.Oauth2GrantStatusApprove",
                "deviceGrantRevokedOrExpired(grant, now) == false"
              ],
              "implementation": "repository.UpdateOauth2DeviceGrant(... RevokedAt ...)"
            },
            {
              "operation": "SELECT",
              "trigger": "Lock and inspect the authorization code grant during code exchange",
              "conditions": [
                "req.GrantType == oauth2_svc.AuthorizationCodeGrantType",
                "req.ValidateCodeGrant() returned nil"
              ],
              "implementation": "CreateAccessTokenByCodeGrant(...) -> repository.GetOauth2CodeGrantWithLock(ctx, tx, code)"
            },
            {
              "operation": "DELETE",
              "trigger": "Delete the authorization code grant after a successful exchange",
              "conditions": [
                "req.GrantType == oauth2_svc.AuthorizationCodeGrantType",
                "createAccessTokenByCodeGrant(...) succeeded"
              ],
              "implementation": "repository.DeleteOauth2CodeGrant(ctx, tx, grant)"
            },
            {
              "operation": "SELECT",
              "trigger": "Lock and inspect the old access token row when refreshing with a refresh token",
              "conditions": [
                "req.GrantType == oauth2_svc.RefreshTokenGrantType",
                "req.ValidateRefreshToken() returned nil"
              ],
              "implementation": "HandleRefreshTokenRequest(...) -> repository.GetOauth2AccessTokenByRefreshTokenWithLock(ctx, tx, encryptedRefreshToken)"
            },
            {
              "operation": "UPDATE",
              "trigger": "Revoke the old access token during refresh-token rotation",
              "conditions": [
                "req.GrantType == oauth2_svc.RefreshTokenGrantType",
                "oldAkObj belongs to the app and the refresh token is not expired"
              ],
              "implementation": "createAccessTokenByRefresh(...) -> repository.UpdateOauth2AccessToken(... RevokedAt ...)"
            },
            {
              "operation": "INSERT",
              "trigger": "Persist the newly generated access token and refresh token row",
              "conditions": [
                "device grant approved path, authorization code path, or refresh token path reaches createAccessTokenWithRetry"
              ],
              "implementation": "createAccessTokenWithRetry(...) -> repository.CreateOauth2AccessToken(ctx, db, obj)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-provider-grpc",
          "target_repo": "tidbcloud/account",
          "target_interface": "AccountAPIService.SaveAuthorizationData",
          "operation_type": "grpc_unary",
          "conditions": [
            "Only after createAccessTokenWithRetry inserts the new token row",
            "Only when accessToken.GrantType == AuthorizationCode",
            "Only when config.IsLocalEnv() == false"
          ],
          "operations": [
            {
              "operation": "RPC CALL",
              "trigger": "Sync authorization data to account after a successful authorization code exchange",
              "conditions": [
                "syncAccessTokenToAccount(...) is reached",
                "accessToken.GrantType == entity.Oauth2AuthorizationCode",
                "config.IsLocalEnv() == false"
              ],
              "implementation": "syncAccessTokenToAccount(...) -> accountProvider.SaveAuthorizationData(ctx, &account.SaveAuthorizationDataReq{...})"
            }
          ]
        }
      ]
    },
    "HTTP POST /v1/revoke": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Request binding and validation succeeded; revoke remains best-effort even when the token is missing or the client secret is wrong"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "trigger": "Load the OAuth2 application by client_id before checking token ownership",
              "conditions": [
                "req.Validate() returned nil"
              ],
              "implementation": "HandleRevokeTokenRequest(...) -> repository.GetOauth2ApplicationByClientID(ctx, db, clientID)"
            },
            {
              "operation": "SELECT",
              "trigger": "Lookup the current token row by access token when token_type_hint is access_token or empty",
              "conditions": [
                "token_type_hint == \"access_token\" or token_type_hint == \"\""
              ],
              "implementation": "revokeByAccessToken(...) -> repository.GetOauth2AccessTokenByAccessToken(ctx, db, encryptedToken)"
            },
            {
              "operation": "SELECT",
              "trigger": "Lookup the current token row by refresh token when token_type_hint is refresh_token",
              "conditions": [
                "token_type_hint == \"refresh_token\""
              ],
              "implementation": "revokeByRefreshToken(...) -> repository.GetOauth2AccessTokenByRefreshToken(ctx, db, encryptedToken)"
            },
            {
              "operation": "UPDATE",
              "trigger": "Mark the matched access token as revoked",
              "conditions": [
                "token row exists",
                "token row belongs to the application",
                "token row is not already revoked"
              ],
              "implementation": "repository.RevokeOauth2AccessToken(ctx, db, akObj.ID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /v1/userinfo": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Authorization header exists, is Bearer-formatted, and the encrypted access token is found plus not expired"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "trigger": "Lookup the access token identity by encrypted bearer token",
              "conditions": [
                "Authorization header starts with \"Bearer \""
              ],
              "implementation": "oauth2Svc.GetUserInfo(...) -> oauth2Svc.GetAccessTokenIdentity(...) -> repository.GetOauth2AccessTokenByAccessToken(ctx, db, encryptedToken)"
            },
            {
              "operation": "SELECT",
              "trigger": "Load the application row to decide whether the client is a TMS/TLMS app",
              "conditions": [
                "access token lookup succeeded"
              ],
              "implementation": "oauth2Svc.GetUserInfo(...) -> oauth2Svc.GetApplicationByID(ctx, accessToken.ApplicationID) -> repository.GetOauth2ApplicationByID(ctx, db, id)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-provider-grpc",
          "target_repo": "tidbcloud/account",
          "target_interface": "AccountAPIService.GetUserByID",
          "operation_type": "grpc_unary",
          "conditions": [
            "Only after access token lookup succeeded"
          ],
          "operations": [
            {
              "operation": "RPC CALL",
              "trigger": "Fetch the user's base profile by user ID",
              "conditions": [
                "accessToken != nil"
              ],
              "implementation": "accountClient.GetUserByID(ctx, &account.GetUserByIDRequest{UserId: accessToken.UserID})"
            }
          ]
        },
        {
          "name": "talent-lms",
          "target_repo": "external/talent-lms",
          "target_interface": "GetTmsUsername",
          "operation_type": "http",
          "conditions": [
            "Only when the application client_id is TMS or TLMS",
            "Only when the email is not a pingcap.com/pingcap.cn address"
          ],
          "operations": [
            {
              "operation": "HTTP GET",
              "trigger": "Resolve TMS username and profile fields by email",
              "conditions": [
                "slice.Contain(pingcapTms, app.ClientID)",
                "regexp.MatchString(pingcap email) == false"
              ],
              "implementation": "setTmsUserInfo(...) -> thirdparty.GetTmsUsername(ctx, email)"
            }
          ]
        },
        {
          "name": "account-provider-grpc",
          "target_repo": "tidbcloud/account",
          "target_interface": "AccountAPIService.GetOrgByID",
          "operation_type": "grpc_unary",
          "conditions": [
            "Only when the application client_id is TMS or TLMS",
            "Only when the email is not a pingcap email",
            "Only when thirdparty.GetTmsUsername returns nil"
          ],
          "operations": [
            {
              "operation": "RPC CALL",
              "trigger": "Fallback to org metadata to fill company name and country when the user does not exist in TMS",
              "conditions": [
                "tmsUser == nil"
              ],
              "implementation": "accountClient.GetOrgByID(ctx, &account.GetOrgByIDRequest{Id: orgId})"
            }
          ]
        }
      ]
    },
    "HTTP GET /v1/authInfo": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Authorization header exists, is Bearer-formatted, and the encrypted access token is found plus not expired"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "trigger": "Lookup the access token identity by encrypted bearer token",
              "conditions": [
                "Authorization header starts with \"Bearer \""
              ],
              "implementation": "oauth2Svc.GetAccessTokenInfo(...) -> oauth2Svc.GetAccessTokenIdentity(...) -> repository.GetOauth2AccessTokenByAccessToken(ctx, db, encryptedToken)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/oauth/device/check": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Inner auth middleware passed and request binding plus request validation succeeded"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "trigger": "Load the device grant by user_code and ensure it is pending, not revoked, and not expired",
              "conditions": [
                "autoBind(&req) succeeded",
                "req.Validate() returned nil"
              ],
              "implementation": "oauth2Svc.HandleInnerDeviceCodeCheckRequest(...) -> repository.GetOauth2DeviceGrantByUserCode(ctx, db, userCode)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-provider-grpc",
          "target_repo": "tidbcloud/account",
          "target_interface": "AccountAPIService.GetUserByToken",
          "operation_type": "grpc_unary",
          "conditions": [
            "Only when config.IsLocalEnv() == false",
            "Runs in the shared inner auth middleware before the handler body"
          ],
          "operations": [
            {
              "operation": "RPC CALL",
              "trigger": "Authenticate the current user via Auth0-based middleware before the inner route is allowed to run",
              "conditions": [
                "config.IsLocalEnv() == false"
              ],
              "implementation": "installAuthPlugin(...) -> tigin.CheckAuthByAuth0(accountClient)"
            }
          ]
        }
      ]
    },
    "HTTP POST /api/v1/oauth/device/confirmation": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Inner auth middleware passed and request binding plus request validation succeeded"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "trigger": "Lock the device grant by user_code before approve/deny mutation",
              "conditions": [
                "autoBind(&req) succeeded",
                "req.Validate() returned nil"
              ],
              "implementation": "HandleInnerDeviceCodeConfirmationRequest(...) -> repository.GetOauth2DeviceGrantByUserCodeWithLock(ctx, tx, userCode)"
            },
            {
              "operation": "UPDATE",
              "trigger": "Approve the device grant and attach user/org identity",
              "conditions": [
                "approve == true",
                "CanApproveOrDenyDeviceGrant(ctx, grant) == true"
              ],
              "implementation": "ApproveOauth2DeviceGrant(...) -> repository.UpdateOauth2DeviceGrant(... Scopes, GrantAllProjects, ProjectIDs, UserID, UserEmail, Status, OrgID ...)"
            },
            {
              "operation": "UPDATE",
              "trigger": "Deny the device grant and mark it revoked",
              "conditions": [
                "approve == false",
                "CanApproveOrDenyDeviceGrant(ctx, grant) == true"
              ],
              "implementation": "DenyOauth2DeviceGrant(...) -> repository.UpdateOauth2DeviceGrant(... RevokedAt, UserID, UserEmail, Status ...)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-provider-grpc",
          "target_repo": "tidbcloud/account",
          "target_interface": "AccountAPIService.GetUserByToken",
          "operation_type": "grpc_unary",
          "conditions": [
            "Only when config.IsLocalEnv() == false",
            "Runs in the shared inner auth middleware before the handler body"
          ],
          "operations": [
            {
              "operation": "RPC CALL",
              "trigger": "Authenticate the current user via Auth0-based middleware before the inner route is allowed to run",
              "conditions": [
                "config.IsLocalEnv() == false"
              ],
              "implementation": "installAuthPlugin(...) -> tigin.CheckAuthByAuth0(accountClient)"
            }
          ]
        },
        {
          "name": "account-provider-grpc",
          "target_repo": "tidbcloud/account",
          "target_interface": "AccountAPIService.ListOrgsByUser",
          "operation_type": "grpc_unary",
          "conditions": [
            "Only when approve == true",
            "Only when config.IsLocalEnv() == false"
          ],
          "operations": [
            {
              "operation": "RPC CALL",
              "trigger": "Check whether the authenticated user belongs to the requested org before approving the device grant",
              "conditions": [
                "approve == true",
                "config.IsLocalEnv() == false"
              ],
              "implementation": "IsUserInOrg(ctx, user, orgId, o.accountProviderClient) -> accountProviderClient.ListOrgsByUser(ctx, &account.ListOrgsByUserRequest{UserId: user.Id})"
            }
          ]
        }
      ]
    },
    "HTTP POST /api/v1/oauth/authorize/check": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Inner auth middleware passed and request binding plus request validation succeeded"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "trigger": "Load the OAuth2 application by client_id before validating redirect URI, response type, and scopes",
              "conditions": [
                "autoBind(&req) succeeded",
                "req.Validate() returned nil"
              ],
              "implementation": "oauth2Svc.InnerAuthorizationCodeRequestValidate(...) -> repository.GetOauth2ApplicationByClientID(ctx, db, clientID)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-provider-grpc",
          "target_repo": "tidbcloud/account",
          "target_interface": "AccountAPIService.GetUserByToken",
          "operation_type": "grpc_unary",
          "conditions": [
            "Only when config.IsLocalEnv() == false",
            "Runs in the shared inner auth middleware before the handler body"
          ],
          "operations": [
            {
              "operation": "RPC CALL",
              "trigger": "Authenticate the current user via Auth0-based middleware before the inner route is allowed to run",
              "conditions": [
                "config.IsLocalEnv() == false"
              ],
              "implementation": "installAuthPlugin(...) -> tigin.CheckAuthByAuth0(accountClient)"
            }
          ]
        }
      ]
    },
    "HTTP POST /api/v1/oauth/authorize/confirmation": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Inner auth middleware passed and request binding plus request validation succeeded"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "trigger": "Load the OAuth2 application by client_id while validating the authorization request",
              "conditions": [
                "autoBind(&req) succeeded",
                "req.Validate() returned nil"
              ],
              "implementation": "oauth2Svc.InnerAuthorizationCodeRequestValidate(...) -> repository.GetOauth2ApplicationByClientID(ctx, db, clientID)"
            },
            {
              "operation": "INSERT",
              "trigger": "Create the authorization code grant after the authenticated user passes org/project permission checks",
              "conditions": [
                "InnerAuthorizationCodeRequestValidate(...) returned authorizeReq",
                "checkUserScopeOrgProjectsPermission(...) returned nil"
              ],
              "implementation": "oauth2Svc.InnerAuthorizationCodeApprove(...) -> repository.CreateOauth2CodeGrant(ctx, db, grantObj)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-provider-grpc",
          "target_repo": "tidbcloud/account",
          "target_interface": "AccountAPIService.GetUserByToken",
          "operation_type": "grpc_unary",
          "conditions": [
            "Only when config.IsLocalEnv() == false",
            "Runs in the shared inner auth middleware before the handler body"
          ],
          "operations": [
            {
              "operation": "RPC CALL",
              "trigger": "Authenticate the current user via Auth0-based middleware before the inner route is allowed to run",
              "conditions": [
                "config.IsLocalEnv() == false"
              ],
              "implementation": "installAuthPlugin(...) -> tigin.CheckAuthByAuth0(accountClient)"
            }
          ]
        },
        {
          "name": "account-provider-grpc",
          "target_repo": "tidbcloud/account",
          "target_interface": "AccountAPIService.VerifyUserOrgAndProjects",
          "operation_type": "grpc_unary",
          "conditions": [
            "Only when config.IsLocalEnv() == false"
          ],
          "operations": [
            {
              "operation": "RPC CALL",
              "trigger": "Verify that the current user can authorize the requested org and project scopes before creating the code grant",
              "conditions": [
                "config.IsLocalEnv() == false"
              ],
              "implementation": "checkUserScopeOrgProjectsPermission(...) -> o.accountProviderClient.VerifyUserOrgAndProjects(ctx, &account.VerifyUserOrgAndProjectsReq{...})"
            }
          ]
        }
      ]
    },
    "HTTP GET /api/v1/oauth/console/token": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Inner auth middleware passed and request binding plus request validation succeeded"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "trigger": "Load the latest access token for the current user and application",
              "conditions": [
                "autoBind(&req) succeeded",
                "req.Validate() returned nil"
              ],
              "implementation": "oauth2Svc.GetUserLastAccessToken(ctx, filter) -> repository.GetUserLastAccessToken(ctx, db, req)"
            },
            {
              "operation": "SELECT",
              "trigger": "Load the application row to expose company metadata for the token response",
              "conditions": [
                "token.ID != 0"
              ],
              "implementation": "oauth2Svc.GetApplicationByID(ctx, token.ApplicationID) -> repository.GetOauth2ApplicationByID(ctx, db, id)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-provider-grpc",
          "target_repo": "tidbcloud/account",
          "target_interface": "AccountAPIService.GetUserByToken",
          "operation_type": "grpc_unary",
          "conditions": [
            "Only when config.IsLocalEnv() == false",
            "Runs in the shared inner auth middleware before the handler body"
          ],
          "operations": [
            {
              "operation": "RPC CALL",
              "trigger": "Authenticate the current user via Auth0-based middleware before the inner route is allowed to run",
              "conditions": [
                "config.IsLocalEnv() == false"
              ],
              "implementation": "installAuthPlugin(...) -> tigin.CheckAuthByAuth0(accountClient)"
            }
          ]
        },
        {
          "name": "account-provider-grpc",
          "target_repo": "tidbcloud/account",
          "target_interface": "AccountAPIService.GetScopeUser",
          "operation_type": "grpc_unary",
          "conditions": [
            "Only when token.ID != 0",
            "Only when token.GrantType == Oauth2DeviceCode"
          ],
          "operations": [
            {
              "operation": "RPC CALL",
              "trigger": "Resolve the user's org role to override the scopes shown for device-code tokens",
              "conditions": [
                "token.GrantType == entity.Oauth2DeviceCode"
              ],
              "implementation": "accountClient.GetScopeUser(ctx, &account.GetScopeUserRequest{ScopeType: SCOPE_TYPE_ORG, ScopeId: token.OrgID, UserId: token.UserID})"
            }
          ]
        }
      ]
    },
    "HTTP POST /api/v1/oauth/console/token": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Inner auth middleware passed and request binding plus request validation succeeded"
          ],
          "operations": [
            {
              "operation": "UPDATE",
              "trigger": "Revoke matching tokens for the current user and application",
              "conditions": [
                "autoBind(&req) succeeded",
                "req.Validate() returned nil"
              ],
              "implementation": "oauth2Svc.RevokeTokenByFilter(ctx, filter) -> repository.RevokeOauth2AccessTokenByFilter(ctx, db, req)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-provider-grpc",
          "target_repo": "tidbcloud/account",
          "target_interface": "AccountAPIService.GetUserByToken",
          "operation_type": "grpc_unary",
          "conditions": [
            "Only when config.IsLocalEnv() == false",
            "Runs in the shared inner auth middleware before the handler body"
          ],
          "operations": [
            {
              "operation": "RPC CALL",
              "trigger": "Authenticate the current user via Auth0-based middleware before the inner route is allowed to run",
              "conditions": [
                "config.IsLocalEnv() == false"
              ],
              "implementation": "installAuthPlugin(...) -> tigin.CheckAuthByAuth0(accountClient)"
            }
          ]
        }
      ]
    },
    "HTTP GET /api/v1/oauth/console/application/user-authorized": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Inner auth middleware passed"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "trigger": "Load all cloud OAuth2 applications",
              "conditions": [
                "Always after middleware success"
              ],
              "implementation": "oauth2Svc.QueryOauth2Applications(ctx, QueryAppsParam{Types: []ApplicationType{Cloud}}) -> repository.QueryOauth2Applications(ctx, db, filter)"
            },
            {
              "operation": "SELECT",
              "trigger": "Load the set of applications already authorized by the current user",
              "conditions": [
                "Always after middleware success"
              ],
              "implementation": "oauth2Svc.InnerQueryUserAuthorizedApplications(ctx, UserAuthorizedAppsFilter{UserId: user.Id}) -> repository.QueryUserAuthorizedApplications(ctx, db, req)"
            },
            {
              "operation": "SELECT",
              "trigger": "For each app that is already authorized, load the user's latest non-expired access token to derive last-used metadata",
              "conditions": [
                "Per cloud app",
                "slice.ContainBy(authorizedApps, isEven) == true"
              ],
              "implementation": "oauth2Svc.GetUserLastAccessToken(ctx, TokenFilter{UserId: user.Id, ApplicationId: uint64(app.ID)}) -> repository.GetUserLastAccessToken(ctx, db, req)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-provider-grpc",
          "target_repo": "tidbcloud/account",
          "target_interface": "AccountAPIService.GetUserByToken",
          "operation_type": "grpc_unary",
          "conditions": [
            "Only when config.IsLocalEnv() == false",
            "Runs in the shared inner auth middleware before the handler body"
          ],
          "operations": [
            {
              "operation": "RPC CALL",
              "trigger": "Authenticate the current user via Auth0-based middleware before the inner route is allowed to run",
              "conditions": [
                "config.IsLocalEnv() == false"
              ],
              "implementation": "installAuthPlugin(...) -> tigin.CheckAuthByAuth0(accountClient)"
            }
          ]
        }
      ]
    },
    "HTTP POST /api/v1/oauth/console/application": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Inner auth middleware passed, operator email is whitelisted, request JSON parsed successfully, and app fields are valid"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "trigger": "Check whether the requested application name already exists",
              "conditions": [
                "emailWhitelist contains user.Email",
                "ShouldBindJSON(&createAppReq) succeeded",
                "createAppReq.Name != \"\"",
                "createAppReq.RedirectURI != \"\"",
                "GrantTypeFormString[createAppReq.GrantType] resolved"
              ],
              "implementation": "oauth2Svc.CreateApplication(...) -> repository.IsOauth2ApplicationNameExists(ctx, db, name)"
            },
            {
              "operation": "INSERT",
              "trigger": "Persist the newly generated OAuth2 application row with encrypted client secret",
              "conditions": [
                "application name does not exist"
              ],
              "implementation": "oauth2Svc.CreateApplication(...) -> repository.CreateOauth2Application(ctx, db, obj)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-provider-grpc",
          "target_repo": "tidbcloud/account",
          "target_interface": "AccountAPIService.GetUserByToken",
          "operation_type": "grpc_unary",
          "conditions": [
            "Only when config.IsLocalEnv() == false",
            "Runs in the shared inner auth middleware before the handler body"
          ],
          "operations": [
            {
              "operation": "RPC CALL",
              "trigger": "Authenticate the current user via Auth0-based middleware before the inner route is allowed to run",
              "conditions": [
                "config.IsLocalEnv() == false"
              ],
              "implementation": "installAuthPlugin(...) -> tigin.CheckAuthByAuth0(accountClient)"
            }
          ]
        }
      ]
    },
    "AuthServerGRPCLifecycle.Startup": {
      "infrastructure": {},
      "services": []
    },
    "AuthServerGRPCLifecycle.InitializeTracing": {
      "infrastructure": {},
      "services": []
    },
    "AuthServerGRPCLifecycle.InitializeLoggerAndSentry": {
      "infrastructure": {},
      "services": []
    },
    "AuthServerGRPCLifecycle.InitializeDatabase": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Always in grpc mode"
          ],
          "operations": [
            {
              "operation": "OPEN DB HANDLE",
              "trigger": "Connect to MySQL using DB_PASSWORD plus MysqlConfig from the loaded config",
              "conditions": [
                "os.Getenv(\"DB_PASSWORD\") != \"\""
              ],
              "implementation": "database.Connect(ctx, centralConfig) -> gorm.Open(mysql.Open(url), &gorm.Config{TablePrefix: \"auth_server_\"})"
            }
          ]
        }
      },
      "services": []
    },
    "AuthServerGRPCLifecycle.InitializeContainer": {
      "infrastructure": {},
      "services": [
        {
          "name": "account-provider-grpc",
          "target_repo": "tidbcloud/account",
          "target_interface": "AccountAPIService",
          "operation_type": "grpc_connect",
          "conditions": [
            "Always in grpc mode"
          ],
          "operations": [
            {
              "operation": "CONNECT",
              "trigger": "Initialize the shared AccountAPIService client used by the provider controller's OAuth2 service",
              "conditions": [
                "container.InitGlobalContainer(database.DBConn.DB) is reached"
              ],
              "implementation": "container.initExternalService() -> grpc.GetAccountProviderSvcClient() -> tigrpc.NewClientConn(config.Global().GrpcConfig.AccountProviderSvcAddr, tigrpc.WithDefault())"
            }
          ]
        }
      ]
    },
    "AuthServerGRPCLifecycle.StartMetricsServer": {
      "infrastructure": {},
      "services": []
    },
    "AuthServerGRPCLifecycle.StartGRPCServer": {
      "infrastructure": {},
      "services": []
    },
    "AuthServerProviderGRPC.GetIdentityByAccessToken": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only when req.RawAccessToken != \"\""
          ],
          "operations": [
            {
              "operation": "SELECT",
              "trigger": "Lookup the access token identity by encrypted raw access token",
              "conditions": [
                "req.RawAccessToken != \"\""
              ],
              "implementation": "providerControllerImpl.GetIdentityByAccessToken(...) -> oauth2Svc.GetAccessTokenIdentity(ctx, req.RawAccessToken) -> repository.GetOauth2AccessTokenByAccessToken(ctx, db, encryptedToken)"
            }
          ]
        }
      },
      "services": []
    },
    "AuthServerMigrateLifecycle.RunMigrations": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Always in migrate mode"
          ],
          "operations": [
            {
              "operation": "OPEN DB HANDLE",
              "trigger": "Connect to MySQL before running auth-server schema migrations",
              "conditions": [
                "os.Getenv(\"DB_PASSWORD\") != \"\""
              ],
              "implementation": "database.Connect(ctx, centralConfig)"
            },
            {
              "operation": "AUTO MIGRATE",
              "trigger": "Initialize the base auth-server schema for oauth2 tables",
              "conditions": [
                "migrate.RunAuthServerDBMigrate(database.DBConn.DB) is reached"
              ],
              "implementation": "migrate.initAuthServerDB(db) -> db.AutoMigrate(&Oauth2Application{}, &Oauth2DeviceGrant{}, &Oauth2AccessToken{}, &Oauth2CodeGrant{})"
            },
            {
              "operation": "RUN MIGRATION QUEUE",
              "trigger": "Apply ordered gormigrate records tracked in auth_server_migrations",
              "conditions": [
                "migrate.RunAuthServerDBMigrate(database.DBConn.DB) is reached"
              ],
              "implementation": "migrate.doMigrate(db, initAuthServerDB, authserverDBMigrationRecords) -> gormigrate.New(...).Migrate()"
            }
          ]
        }
      },
      "services": []
    }
  }
}
