RBAC, Authentication & Token Management
Table of Contents
- 1. Login
- 2. Token Types
- 3. Creating User Tokens (Login Flow)
- 4. Creating API Tokens
- 5. Roles Overview
- 6. Permissions Table
- 7. Subject Scoping
- 8. Token Lifecycle
1. Login
Authentication is performed via OpenID Connect (OIDC). The metal-apiserver supports OIDC providers configured at deployment time (e.g. GitHub, GitLab, or any generic OIDC provider). The login flow uses the goth library for provider integration.
1.1 How Login Works
- The user navigates to the login endpoint, which initiates the OIDC authorization flow.
- The user is redirected to the OIDC provider's login page.
- After the provider authenticates the user, the user is redirected back via the provider callback URL.
- The server validates the OIDC tokens, extracts the user's unique login identifier (the
subclaim, configurable viauniqueUserKey), and looks up or creates the corresponding tenant. - A user token is generated and appended to the redirect URL as a
tokenquery parameter (e.g.?token=eyJhbGc...). - With such a user token a user can create api tokens for specific use cases with restricted capabilities which services can be called.
1.2 Login HTTP Endpoints
| Endpoint | Method | Description |
|---|---|---|
/auth/login | GET | Starts the OIDC authorization flow. An optional redirect-url query parameter specifies where to return after login. |
/auth/callback | GET | OIDC provider callback. The server receives the authorization code, exchanges it for tokens, creates the user token, and redirects to the redirect-url with the token appended. |
/auth/logout | GET | Terminates the session. Optionally redirects to the provider's end-session URL. |
1.3 Login Constraints
- Tenant auto-creation: On first login, if the user does not have a tenant, one is automatically created with the same ID as the user's login. The user is granted
OWNERrole on their own tenant. - Provider tenant: Users who are members of the configured provider tenant receive admin-level roles (
ADMIN_ROLE_EDITORorADMIN_ROLE_VIEWER), depending on their provider tenant membership level. These admin roles must be explicitly ordered and are not granted automatically on login. - Redirect URL validation: The
redirect-urlparameter must match a configured allowlist of allowed redirect URLs (same scheme and hostname).
2. Token Types
| Token Type | Constant | Purpose |
|---|---|---|
| User Token | TOKEN_TYPE_USER | Created during the interactive login flow. Contains the user's implicit roles from the tenant-API-server. Used by human users interacting with the API (e.g. through console or CLI). User tokens do not store AdminRole, TenantRoles, ProjectRoles, or Permissions -- these are resolved dynamically from the tenant-API-server at request time. |
| API Token | TOKEN_TYPE_API | Created programmatically via the Token API (TokenService.Create, TokenService.Refresh, or the server CLI). Used by applications that interact with the metal-stack API, CI/CD pipelines, and automation. Stores all permissions explicitly embedded in the JWT. |
Key difference: A User Token carries dynamic role enforcement resolved at runtime from the tenant-API-server (the tenant-apiserver that manages tenant/project memberships). An API Token carries static, self-contained permissions directly in the JWT payload. This means API tokens can be given fine-grained custom permissions that are not tied to tenant-project membership. Note that API tokens are additionally checked against the implicit user permissions of the token owner from the tenant-API-server, too. This check prevents that an API token can access resources after a tenant membership was removed or modified.
3. Creating User Tokens (Login Flow)
3.1 Via the Web UI (Console Login)
- Open the web UI and navigate to the login page.
- Authenticate with your OIDC provider.
- Upon successful authentication, you are redirected with a token appended to the URL.
- The token is automatically used for subsequent authenticated API calls or UI operations.
3.2 Via the CLI (metalctl login)
- Run
metalctl login --api-url <reachable apiserver endpoint> --provider openid-connect - A browser will open and you are prompted for your credentials.
- With successful authentication, you are redirected with the token and the cli will store them in
~/.metal-stack/config.yaml. - Subsequent calls with metalctl will be authenticated with the token stored in the configuration.
- api-url and provider are stored in the config.yaml. Further logins do not require them anymore.
3.3 Via the api-server CLI (api-server token create)
The server provides a CLI command for creating tokens programmatically without web-based OIDC:
api-server token create <subject>
Internally this calls CreateApiTokenWithoutPermissionCheck which:
- Uses the default expiration if none is specified.
- Creates a
TOKEN_TYPE_APItoken. - Can optionally accept
--project-roles,--tenant-roles,--admin-role,--infra-role,--machine-roles,--permissions, and--expiresflags.
A cronjob with the apiserver images is executed every 8h and create a ADMIN_ROLE_EDITOR and a ADMIN_ROLE_VIEWER token and store it in a Secret metal-apiserver-admin-token
The tokens in this secret expire after 16h and can be used e.g. for IaC automation jobs which need a token with admin role to create other tokens for services for example.
Note that the api-server CLI is intended to be used for bootstrapping mechanisms only as it skips the token permission check. Please do not build up on this mechanism internally for creating tokens.
4. Creating API Tokens
API tokens are managed through the Token Service API. They are JWTs that carry explicit role assignments and permissions.
4.1 Token Service Endpoints
| Procedure | Description |
|---|---|
TokenService.Create | Creates a new API token with the specified roles and permissions. |
TokenService.Refresh | Refreshes an existing token (re-issue with the same permissions and duration, but a new JWT and secret). |
TokenService.Update | Updates an existing API token's roles, permissions, or description. Only updates to roles/permissions the caller already possesses are allowed. |
TokenService.Get | Retrieves a specific token by UUID (only its own tokens). |
TokenService.List | Lists all tokens belonging to the authenticated user. |
TokenService.Revoke | Revokes (deletes) a token. |
4.2 Token Creation Request Fields
When calling TokenService.Create, you must provide a TokenServiceCreateRequest with the following optional fields:
| Field | Type | Description |
|---|---|---|
expires | google.protobuf.Duration | Token validity period. Must not exceed MaxTokenExpiration (server configuration). |
description | string | Human-readable description for identification. |
admin_role | AdminRole | Admin-level role (see Section 5). |
infra_role | InfraRole | Infrastructure-level role (see Section 5). |
project_roles | map<string, ProjectRole> | Map of project ID to role (e.g. {"my-project": "PROJECT_ROLE_OWNER"}). Use "*" for any projects that the requester is member of. |
tenant_roles | map<string, TenantRole> | Map of tenant ID to role (e.g. {"my-tenant": "TENANT_ROLE_EDITOR"}). Use "*" for any tenants that the requester is member of. |
machine_roles | map<string, MachineRole> | Map of machine UUID to role (e.g. {"<uuid>": "MACHINE_ROLE_OWNER"}). Use "*" for any machine. |
permissions | MethodPermission[] | Custom fine-grained permissions, each specifying a subject, methods list (e.g. [{"subject": "my-project", "methods": ["metalstack.api.v2.MachineService/List"]}]). |
4.3 Permission Elevation Prevention
Token creation enforces a no-elevation rule: the caller's token must already possess sufficient permissions to authorize every requested role/permission in the new token. This prevents privilege escalation. The validation works as follows:
- If the requesting user is a member of the provider tenant, they can request an admin role only up to the level of their own provider-tenant membership, see table 5.1 below.
- For project-scoped roles, the user must already have a role in the target project (or use
"*"for future/unknown projects). The same applies to tenants and machines. - Custom
MethodPermissionentries must reference methods the user can already call. - Every requested subject (tenant, project, machine) must either be one the user already has access to, or
"*"(wildcard).
5. Roles Overview
Roles in the metal-apiserver follow a hierarchical structure across multiple scopes:
5.1 Admin Roles (Unscoped -- Apply Globally)
Admin roles are the highest privilege level and apply to all subjects.
| Role | Description |
|---|---|
ADMIN_ROLE_EDITOR | Full editor access to all resources (projects, tenants, components, partitions, switches, ...). Can read, create, update, and delete. |
ADMIN_ROLE_VIEWER | Read-only access across all resources. Cannot create, update, or delete anything. |
Important: Only members of the provider tenant can hold admin roles. The provider tenant role determines the maximum admin role:
TENANT_ROLE_OWNERin the provider tenant --> maximum admin role isADMIN_ROLE_EDITORTENANT_ROLE_EDITORorTENANT_ROLE_VIEWERin the provider tenant --> maximum admin role isADMIN_ROLE_VIEWER
5.2 Tenant Roles (Tenant-Scoped)
| Role | Description |
|---|---|
TENANT_ROLE_OWNER | Full control over the tenant and all its projects. |
TENANT_ROLE_EDITOR | Can manage resources within the tenant. |
TENANT_ROLE_VIEWER | Read-only access within the tenant. |
TENANT_ROLE_GUEST | Very restricted view on the tenant's properties. This role is gained implicitly through a direct project membership within a tenant. |
5.3 Project Roles (Project-Scoped)
| Role | Description |
|---|---|
PROJECT_ROLE_OWNER | Full control over the project. |
PROJECT_ROLE_EDITOR | Can manage resources within the project. |
PROJECT_ROLE_VIEWER | Read-only access within the project. |
Note that a tenant membership implicitly grants projects roles. For instance, when a user is an editor of a tenant, he implicitly gains editor project permissions on all of the tenant's projects without requiring to request direct project memberships.
5.4 Infrastructure Roles (Unscoped -- Infrastructure Level)
| Role | Description |
|---|---|
INFRA_ROLE_EDITOR | Full editor access to infra API procedures. |
INFRA_ROLE_VIEWER | Read-only access to infra API procedures. |
5.5 Machine Roles (Machine-Scoped, per UUID)
| Role | Description |
|---|---|
MACHINE_ROLE_EDITOR | Full editor access to infra machine API procedures. |
MACHINE_ROLE_VIEWER | Read-only access to infra machine API procedures. |
6. Permissions Table
TBD
7. Subject Scoping
Every method in the metal-apiserver is categorized by its scope, which determines how the subject (resource identifier) is checked:
| Category | Method Scoping | Authorization Logic |
|---|---|---|
| Public | No subject required | Accessible to everyone, including unauthenticated requests |
| Self | Subject = authenticated user token's user field | Only the token's owner can call. Used for /user, /token operations |
| Project | Subject = project ID from request | Requester must have project-level role for that specific project ID |
| Tenant | Subject = tenant ID from request | Requester must have tenant-level role for that specific tenant ID |
| Machine | Subject = machine UUID from request | Requester token must have machine-level role for that specific machine UUID (or wildcard *) |
Wildcard * Subject in Token Permissions
When a token contains * as a subject for a given role, it means the token has access to all subjects of that scope. For example:
project_roles: {"*": "PROJECT_ROLE_EDITOR"}grants project editor access to all current and future projects the requester has access to.tenant_roles: {"*": "TENANT_ROLE_EDITOR"}grants tenant editor access to all current and future tenants the requester has access to.
Permission Elevation and Wildcards
During token creation, a user cannot specify a wildcard * unless their own token also has * for the same scope, OR the user has the specific role on that subject. Wildcards allow tokens to work with resources that don't exist yet (e.g. future projects).
TODO: How to gain a * permission initially as a user.
8. Token Lifecycle
8.1 Token Structure
Tokens are JWT (JSON Web Tokens) signed with an X.509 private key. Each token carries:
aud([]string): The intended audience (statically set to[<api-server-endpoint>])exp(timestamp): Expiration timeiat(timestamp): Issued-at timeiss(string): Token issuerjti(string): JWT Token UUIDnbf(timestamp): Time when the token becomes validsub(string): The user/login who owns this tokentype(string): The token type as described in the token types section
In the backend, additional information on the token permissions are stored:
admin_role(AdminRole_enum): Admin-level roleinfra_role(InfraRole_enum): Infrastructure-level roleproject_roles(map<string, ProjectRole_enum>): Project-scoped rolestenant_roles(map<string, TenantRole_enum>): Tenant-scoped rolesmachine_roles(map<string, MachineRole_enum>): Machine-scoped rolespermissions(MethodPermission[]): Custom fine-grained permissionsdescription(string): Human-readable labellabels(map<string, string>): Token metadata labels
8.2 Token Expiration
- User tokens created via login use a default expiration of 8 hours.
- API tokens have a configurable expiration set during creation. The maximum allowed expiration is defined by the server's
MaxTokenExpirationsetting.
8.3 Token Refresh
The Refresh operation creates a new JWT with the exact same roles and permissions as the original token, giving the consumer a fresh exp time while retaining all capabilities. It requires the calling token to already have the permissions to authorize the requested roles. Token must contain the required permissions TokenService/Refresh to call the refresh endpoint.
8.4 Token Revocation
To revoke a token, call TokenService/Revoke with the token's UUID. After revocation, the token is removed from the token store and all subsequent API calls using it will fail with an authorization error. The revocation is effective immediately on the next request.
8.5 Certificate Rotation
Tokens are signed using X.509 certificates managed by the server's certificate store. During rotation, new tokens are signed with the latest private key while existing tokens remain valid until they expire (since old certificates are still used for verification). The signing certificate is fetched at token creation time from t.certs.LatestPrivate(ctx) (see pkg/service/api/token/token-service.go:85). This mechanism defines the maximum token expiration length.
8.6 Token Storage
Each user can manage their own tokens. Tokens are listed with TokenService/List. Users can only see, update, and delete their own tokens. Admin users can create/list/delete tokens on behalf of other users.
Appendix A: Token Creation Decision Flow
When a user creates an API token, this decision flow determines whether the operation is allowed:
Note that this flow is not fully complete but gives an insight to the implementation.
1. Is the calling token a valid USER or API token type?
No --> error: "invalid token type for token creation"
Yes --> continue
2. Does the expiration exceed MaxTokenExpiration?
Yes --> error: "requested expiration duration exceeds max"
No --> continue
3. Is the caller a provider-tenant member?
Yes --> resolve their admin role (EDITOR or VIEWER based on provider-tenant membership)
No --> no admin role assigned
4. If admin role is requested:
- Is caller allowed to have the requested admin role?
No --> error: "not member of provider tenant"
Yes --> continue
5. validateTokenRequest (permission elevation prevention):
- Are all requested tenant IDs either "*" or allowed for the caller?
No --> error: "requested tenant roles are not allowed"
- Are all requested tenant role types valid (not UNSPECIFIED)?
No --> error: "requested tenant role is not allowed"
- Are all requested project IDs either "*" or allowed for the caller?
No --> error: "requested project roles are not allowed"
- Are all requested project role types valid?
No --> error: "requested project role is not allowed"
- Do all custom MethodPermission methods exist?
No --> error: "unknown method X"
- Are all requested machine UUIDs either "*" or allowed for the caller?
No --> error: "requested machine roles are not allowed"
6. For each method in the requested permission set:
- Does the caller already have permission to this method?
No --> error: "the following method is not allowed"
- If the method is subject-scoped:
Does the caller have authority over the requested subject?
No --> error: "method X is not allowed on subject Y"
Yes --> proceed
7. Create JWT with all roles and permissions, sign with latest private key
Appendix B: Token Update Rules
Token updates follow the same elevation-prevention logic as creation. Additionally:
- Only tokens of type
TOKEN_TYPE_APIcan be updated (not user tokens). - The update requires the calling token to possess permissions that cover all permissions on the updated token.
- Users cannot grant permissions to a token that they themselves do not possess.
Appendix C: Token Refresh Rules
- Refresh re-issues the token with the same permissions.
- The new token's expiration is calculated as:
original_expiry - original_issued_at(preserving the original duration). - All role assignments from the old token are copied to the new token.
- The caller's current permissions (not the old token's) are validated against the requested permissions (which are the same as the old token's, so this is effectively a verification step).