1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
15 "git.arvados.org/arvados.git/lib/ctrlctx"
16 "git.arvados.org/arvados.git/sdk/go/arvados"
17 "git.arvados.org/arvados.git/sdk/go/auth"
18 "git.arvados.org/arvados.git/sdk/go/ctxlog"
19 "git.arvados.org/arvados.git/sdk/go/httpserver"
22 func logout(ctx context.Context, cluster *arvados.Cluster, opts arvados.LogoutOptions) (arvados.LogoutResponse, error) {
23 err := expireAPIClientAuthorization(ctx)
25 ctxlog.FromContext(ctx).Errorf("attempting to expire token on logout: %q", err)
26 return arvados.LogoutResponse{}, httpserver.ErrorWithStatus(errors.New("could not expire token on logout"), http.StatusInternalServerError)
29 target := opts.ReturnTo
31 if cluster.Services.Workbench2.ExternalURL.Host != "" {
32 target = cluster.Services.Workbench2.ExternalURL.String()
34 target = cluster.Services.Workbench1.ExternalURL.String()
37 return arvados.LogoutResponse{RedirectLocation: target}, nil
40 func expireAPIClientAuthorization(ctx context.Context) error {
41 creds, ok := auth.FromContext(ctx)
43 // Tests could be passing empty contexts
44 ctxlog.FromContext(ctx).Debugf("expireAPIClientAuthorization: credentials not found from context")
48 if len(creds.Tokens) == 0 {
49 // Old client may not have provided the token to expire
53 tx, err := ctrlctx.CurrentTx(ctx)
58 token := creds.Tokens[0]
61 if strings.HasPrefix(token, "v2/") {
62 tokenParts := strings.Split(token, "/")
63 if len(tokenParts) >= 3 {
64 tokenUuid = tokenParts[1]
65 tokenSecret = tokenParts[2]
69 var retrievedUuid string
70 err = tx.QueryRowContext(ctx, `SELECT uuid FROM api_client_authorizations WHERE api_token=$1 AND (expires_at IS NULL OR expires_at > current_timestamp AT TIME ZONE 'UTC') LIMIT 1`, tokenSecret).Scan(&retrievedUuid)
71 if err == sql.ErrNoRows {
72 ctxlog.FromContext(ctx).Debugf("expireAPIClientAuthorization(%s): not found in database", token)
74 } else if err != nil {
75 ctxlog.FromContext(ctx).WithError(err).Debugf("expireAPIClientAuthorization(%s): database error", token)
79 if tokenUuid != "" && retrievedUuid != tokenUuid {
80 // secret part matches, but UUID doesn't -- somewhat surprising
81 ctxlog.FromContext(ctx).Debugf("expireAPIClientAuthorization(%s): secret part found, but with different UUID: %s", tokenSecret, retrievedUuid)
85 res, err := tx.ExecContext(ctx, "UPDATE api_client_authorizations SET expires_at=current_timestamp AT TIME ZONE 'UTC' WHERE uuid=$1", retrievedUuid)
90 rows, err := res.RowsAffected()
95 ctxlog.FromContext(ctx).Debugf("expireAPIClientAuthorization(%s): no rows were updated", tokenSecret)
96 return fmt.Errorf("couldn't expire provided token")
98 ctxlog.FromContext(ctx).Debugf("expireAPIClientAuthorization(%s): multiple (%d) rows updated", tokenSecret, rows)
100 ctxlog.FromContext(ctx).Debugf("expireAPIClientAuthorization(%s): ok", tokenSecret)