Creates a new token API key with the given scope and lifetime. @Summary Create token API key @ID create-token-api-key @Security CoderSessionToken @Accept json @Produce json @Tags Users @Param user path string true "User ID, name, or me" @Param request body codersdk.CreateTokenRequest true "Create t
(rw http.ResponseWriter, r *http.Request)
| 38 | // @Success 201 {object} codersdk.GenerateAPIKeyResponse |
| 39 | // @Router /api/v2/users/{user}/keys/tokens [post] |
| 40 | func (api *API) postToken(rw http.ResponseWriter, r *http.Request) { |
| 41 | var ( |
| 42 | ctx = r.Context() |
| 43 | user = httpmw.UserParam(r) |
| 44 | auditor = api.Auditor.Load() |
| 45 | aReq, commitAudit = audit.InitRequest[database.APIKey](rw, &audit.RequestParams{ |
| 46 | Audit: *auditor, |
| 47 | Log: api.Logger, |
| 48 | Request: r, |
| 49 | Action: database.AuditActionCreate, |
| 50 | }) |
| 51 | ) |
| 52 | aReq.Old = database.APIKey{} |
| 53 | defer commitAudit() |
| 54 | |
| 55 | var createToken codersdk.CreateTokenRequest |
| 56 | if !httpapi.Read(ctx, rw, r, &createToken) { |
| 57 | return |
| 58 | } |
| 59 | |
| 60 | // TODO(Cian): System users technically just have the 'member' role |
| 61 | // and we don't want to disallow all members from creating API keys. |
| 62 | if user.IsSystem { |
| 63 | api.Logger.Warn(ctx, "disallowed creating api key for system user", slog.F("user_id", user.ID)) |
| 64 | httpapi.Forbidden(rw) |
| 65 | return |
| 66 | } |
| 67 | |
| 68 | // Map and validate requested scope. |
| 69 | // Accept legacy special scopes (all, application_connect) and external scopes. |
| 70 | // Default to coder:all scopes for backward compatibility. |
| 71 | scopes := database.APIKeyScopes{database.ApiKeyScopeCoderAll} |
| 72 | if len(createToken.Scopes) > 0 { |
| 73 | scopes = make(database.APIKeyScopes, 0, len(createToken.Scopes)) |
| 74 | for _, s := range createToken.Scopes { |
| 75 | name := string(s) |
| 76 | if !rbac.IsExternalScope(rbac.ScopeName(name)) { |
| 77 | httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{ |
| 78 | Message: "Failed to create API key.", |
| 79 | Detail: fmt.Sprintf("invalid or unsupported API key scope: %q", name), |
| 80 | }) |
| 81 | return |
| 82 | } |
| 83 | scopes = append(scopes, database.APIKeyScope(name)) |
| 84 | } |
| 85 | } else if string(createToken.Scope) != "" { |
| 86 | name := string(createToken.Scope) |
| 87 | if !rbac.IsExternalScope(rbac.ScopeName(name)) { |
| 88 | httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{ |
| 89 | Message: "Failed to create API key.", |
| 90 | Detail: fmt.Sprintf("invalid or unsupported API key scope: %q", name), |
| 91 | }) |
| 92 | return |
| 93 | } |
| 94 | switch name { |
| 95 | case "all": |
| 96 | scopes = database.APIKeyScopes{database.ApiKeyScopeCoderAll} |
| 97 | case "application_connect": |
nothing calls this directly
no test coverage detected