Move verification to a shared package (#197)

* Move verification to a shared package

The verifier is constructed at HTTP request time and added to the
context. It can then be called from appropriate handlers with
standardized error handling after all the routing.

I intentionally did not add to the handlers yet as I am a good distance
into the scope updates and didn't want to cause even more merge
conflicts. So at the moment authz is again disabled, but once the scope
updates are done, this will be integrated back in.
This commit is contained in:
Jeff Mitchell authored and GitHub committed 2020-07-16 22:12:26 -04:00
1 parent 1514ee1e27
commit 1a1d3058c9
4 files changed
+592 -517

No files matched your search

+304
View File
@@ -0,0 +1,304 @@
package auth
import (
"context"
"errors"
"fmt"
"strings"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/watchtower/internal/perms"
"github.com/hashicorp/watchtower/internal/servers/controller/common"
"github.com/hashicorp/watchtower/internal/types/action"
"github.com/hashicorp/watchtower/internal/types/resource"
"github.com/hashicorp/watchtower/internal/types/scope"
"github.com/kr/pretty"
)
type key int
var verifierKey key
// RequestInfo contains request parameters necessary for checking authn/authz
type RequestInfo struct {
Path string
Method string
PublicId string
Token string
DisableAuthzFailures bool
}
type verifier struct {
logger hclog.Logger
iamRepoFn common.IamRepoFactory
authTokenRepoFn common.AuthTokenRepoFactory
requestInfo RequestInfo
res *perms.Resource
act action.Type
ctx context.Context
}
// NewVerifierContext creates a context that carries a verifier object from the
// HTTP handlers to the gRPC service handlers. It should only be created in the
// HTTP handler and should exist for every request that reaches the service
// handlers.
func NewVerifierContext(ctx context.Context,
logger hclog.Logger,
iamRepoFn common.IamRepoFactory,
authTokenRepoFn common.AuthTokenRepoFactory,
requestInfo RequestInfo) context.Context {
return context.WithValue(ctx, verifierKey, &verifier{
logger: logger,
iamRepoFn: iamRepoFn,
authTokenRepoFn: authTokenRepoFn,
requestInfo: requestInfo,
})
}
// Verify takes in a context that has expected parameters as values and runs an
// authn/authz check. It returns a user ID, the scope ID for the request (which
// may come from the URL and may come from the token) and whether or not to
// proceed, e.g. whether the authn/authz check resulted in failure. If an error
// occurs it's logged to the system log.
func Verify(ctx context.Context) (userId string, scopeId string, valid bool) {
v, ok := ctx.Value(verifierKey).(*verifier)
if !ok {
// We don't have a logger yet and this should never happen in any
// context we won't catch in tests
panic("no verifier information found in context")
}
v.ctx = ctx
if err := v.parseAuthParams(); err != nil {
v.logger.Trace("error reading auth parameters from URL", "url", v.requestInfo.Path, "method", v.requestInfo.Method, "error", err)
return
}
if v.res == nil {
v.logger.Trace("got nil resource information after decorating auth parameters")
return
}
authResults, userId, scopeId, err := v.performAuthCheck()
if err != nil {
v.logger.Error("error performing authn/authz check", "error", err)
return
}
if !authResults.Allowed {
// TODO: Decide whether to remove this
if v.requestInfo.DisableAuthzFailures {
v.logger.Info("failed authz info for request", "resource", pretty.Sprint(v.res), "user_id", userId, "action", v.act.String())
} else {
return
}
}
valid = true
return
}
func (v *verifier) parseAuthParams() error {
// Remove trailing and leading slashes
trimmedPath := strings.Trim(v.requestInfo.Path, "/")
splitPath := strings.Split(strings.TrimPrefix(trimmedPath, "v1"), "/")
splitLen := len(splitPath)
if splitLen == 0 {
return fmt.Errorf("parse auth params: invalid path")
}
var act action.Type
var typStr string
scp := scope.Global
res := &perms.Resource{
ScopeId: scope.Global.String(),
}
// Handle non-custom types. We'll deal with custom types, including list,
// after parsing the path.
switch v.requestInfo.Method {
case "GET":
act = action.Read
case "POST":
act = action.Create
case "PATCH":
act = action.Update
case "DELETE":
act = action.Delete
default:
return fmt.Errorf("parse auth params: unknown method %q", v.requestInfo.Method)
}
// Look for a custom action
colonSplit := strings.Split(splitPath[splitLen-1], ":")
switch len(colonSplit) {
case 1:
// No custom action specified
case 2:
actStr := colonSplit[len(colonSplit)-1]
act = action.Map[actStr]
if act == action.Unknown || act == action.All {
return fmt.Errorf("parse auth params: unknown action %q", actStr)
}
// Keep going with the logic without the custom action
splitPath[splitLen-1] = colonSplit[0]
default:
return fmt.Errorf("parse auth params: unexpected number of colons in last segment %q", colonSplit[len(colonSplit)-1])
}
// Walk backwards. As we walk backwards we look for scopes and figure out if
// we're operating on a resource or a collection. We also populate the pin.
// The rules for the pin are as follows:
//
// * If the last segment is a collection, the pin is the immediately
// preceding ID
//
// * If the last segment is an ID, the pin is the immediately preceding ID
// not including the last segment
//
// * If at the end of the logic the pin is the id of a scope ("global",
// "o_...", "p_...") then there is no pin. The scopes are already enclosing
// so a pin is redundant.
nextIdIsPin := true
for i := splitLen - 1; i >= 0; i-- {
segment := splitPath[i]
// Collections don't contain underscores; every resource ID does.
segmentIsCollection := !strings.Contains(segment, "_")
if !segmentIsCollection && i != splitLen-1 && nextIdIsPin {
res.Pin = segment
nextIdIsPin = false
}
// Update the scope. Set it to org only if it's at global (that way we
// don't override project with org). We have to check if it's one less
// than the length of the split because operating on the id of a scope
// is actually in the enclosing scope (since you're in the parent scope
// operating on a child scope).
switch segment {
case "projects":
if i < splitLen-2 {
scp = scope.Project
res.ScopeId = splitPath[i+1]
}
case "orgs":
if scp == scope.Global {
if i < splitLen-2 {
scp = scope.Org
res.ScopeId = splitPath[i+1]
}
}
}
if segment == "" {
// This could be the case if we have an action like
// /orgs/o_1234/projects/p_1234/:set-defaults to act on the project
// itself but within its own scope
continue
}
if typStr == "" {
// The resource check takes place inside the type check because if
// we've identified the type we have either already identified the
// right-most resource ID or we're operating on a collection, so
// this prevents us from finding a different ID earlier in the path.
//
// We continue on with the enclosing loop anyways though to ensure
// we find the right scope.
if res.Id == "" && !segmentIsCollection {
res.Id = segment
} else {
// Every collection is the plural of the resource type so drop
// the last 's'
if !strings.HasSuffix(segment, "s") {
return fmt.Errorf("parse auth params: invalid collection syntax for %q", segment)
}
typStr = strings.TrimSuffix(segment, "s")
}
}
}
if typStr != "" {
res.Type = resource.Map[typStr]
if res.Type == resource.Unknown {
return fmt.Errorf("parse auth params: unknown resource type %q", typStr)
}
} else if res.Id == "" {
return errors.New("parse auth params: id and type both not found")
}
// If we're operating on a collection (that is, the ID is blank) and it's a
// GET, it's actually a list
if res.Id == "" && act == action.Read {
act = action.List
}
// If the pin ended up being a scope, nil it out
if res.Pin != "" {
if res.Pin == "global" ||
strings.HasPrefix(res.Pin, "o_") ||
strings.HasPrefix(res.Pin, "p_") {
res.Pin = ""
}
}
v.res = res
v.act = act
return nil
}
func (v verifier) performAuthCheck() (aclResults *perms.ACLResults, userId, scopeId string, retErr error) {
// Ensure we return an error by default if we forget to set this somewhere
retErr = errors.New("unknown")
userId = "u_anon"
scopeId = v.res.ScopeId
// Validate the token and fetch the corresponding user ID
tokenRepo, err := v.authTokenRepoFn()
if err != nil {
retErr = fmt.Errorf("perform auth check: failed to get authtoken repo: %w", err)
return
}
at, err := tokenRepo.ValidateToken(v.ctx, v.requestInfo.PublicId, v.requestInfo.Token)
if err != nil {
retErr = fmt.Errorf("perform auth check: failed to validate token: %w", err)
return
}
if at != nil {
userId = at.GetIamUserId()
}
var parsedGrants []perms.Grant
var grantPairs []perms.GrantPair
// Fetch and parse grants for this user ID (which may include grants for
// u_anon and u_auth)
iamRepo, err := v.iamRepoFn()
if err != nil {
retErr = fmt.Errorf("perform auth check: failed to get iam repo: %w", err)
return
}
grantPairs, err = iamRepo.GrantsForUser(v.ctx, userId)
if err != nil {
retErr = fmt.Errorf("perform auth check: failed to query for user grants: %w", err)
return
}
parsedGrants = make([]perms.Grant, 0, len(grantPairs))
for _, pair := range grantPairs {
parsed, err := perms.Parse(pair.ScopeId, userId, pair.Grant)
if err != nil {
retErr = fmt.Errorf("perform auth check: failed to parse grant %#v: %w", pair.Grant, err)
return
}
parsedGrants = append(parsedGrants, parsed)
}
// TODO: When we migrate to scopes, the resource scope ID for this check and
// in the return value needs to be adjusted to the token scope ID for
// actions within the scopes collection
acl := perms.NewACL(parsedGrants...)
allowed := acl.Allowed(*v.res, v.act)
aclResults = &allowed
retErr = nil
return
}
+232
View File
@@ -0,0 +1,232 @@
package auth
import (
"fmt"
"net/http"
"testing"
"github.com/hashicorp/watchtower/internal/types/action"
"github.com/hashicorp/watchtower/internal/types/resource"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestHandler_AuthDecoration(t *testing.T) {
cases := []struct {
name string
path string
method string
action action.Type
scope string
resource resource.Type
id string
pin string
wantErrContains string
}{
{
name: "global scope, read, with id",
path: "/v1/users/u_anon",
method: "GET",
action: action.Read,
scope: "global",
resource: resource.User,
id: "u_anon",
},
{
name: "global scope, update, with id",
path: "/v1/auth-methods/am_1234",
method: "PATCH",
action: action.Update,
scope: "global",
resource: resource.AuthMethod,
id: "am_1234",
},
{
name: "global scope, delete",
path: "/v1/orgs/o_1234",
method: "DELETE",
action: action.Delete,
scope: "global",
resource: resource.Org,
id: "o_1234",
},
{
name: "global scope, create",
path: "/v1/roles",
method: "POST",
action: action.Create,
scope: "global",
resource: resource.Role,
},
{
name: "global, invalid collection syntax",
path: "/v1/org",
wantErrContains: "invalid collection syntax",
},
{
name: "global, custom action",
path: "/v1/orgs/o_123/auth-methods/am_1234:authenticate",
method: "POST",
action: action.Authenticate,
scope: "o_123",
resource: resource.AuthMethod,
id: "am_1234",
},
{
name: "root, unknown action",
path: "/v1/:authentifake",
wantErrContains: "unknown action",
},
{
name: "root, unknown empty action",
path: "/v1/:",
wantErrContains: "unknown action",
},
{
name: "root, invalid method",
path: "/v1/:authenticate",
method: "FOOBAR",
wantErrContains: "unknown method",
},
{
name: "root, wrong number of colons",
path: "/v1/:auth:enticate",
wantErrContains: "unexpected number of colons",
},
{
name: "org scope, valid",
path: "/v1/orgs/o_abc123/auth-methods",
method: "POST",
action: action.Create,
scope: "o_abc123",
resource: resource.AuthMethod,
},
{
name: "project scope, valid",
path: "/v1/orgs/o_abc123/projects/p_1234/host-catalogs",
method: "POST",
action: action.Create,
scope: "p_1234",
resource: resource.HostCatalog,
},
{
name: "project scope, action on project",
path: "/v1/orgs/o_abc123/projects/p_1234/:set-principals",
method: "POST",
action: action.SetPrincipals,
scope: "p_1234",
resource: resource.Project,
id: "p_1234",
},
{
name: "org scope, action on project",
path: "/v1/orgs/o_abc123/projects/p_1234:set-principals",
method: "POST",
action: action.SetPrincipals,
scope: "o_abc123",
resource: resource.Project,
id: "p_1234",
},
{
name: "org scope, get on collection is list",
path: "/v1/orgs/o_abc123/projects",
action: action.List,
scope: "o_abc123",
resource: resource.Project,
},
{
name: "org scope, action on org",
path: "/v1/orgs/o_abc123/:deauthenticate",
action: action.Deauthenticate,
scope: "o_abc123",
resource: resource.Org,
id: "o_abc123",
},
{
name: "top level action, invalid",
path: "/v1/:read",
wantErrContains: "id and type both not found",
},
{
name: "top level, invalid",
path: "/v1/",
wantErrContains: "id and type both not found",
},
{
name: "non-api path",
path: "/",
wantErrContains: "id and type both not found",
},
{
name: "project scope, pinning collection",
path: "/v1/orgs/o_abc123/projects/p_1234/host-catalogs/hc_1234/host-sets",
action: action.List,
scope: "p_1234",
pin: "hc_1234",
resource: resource.HostSet,
},
{
name: "project scope, pinning collection, custom action",
path: "/v1/orgs/o_abc123/projects/p_1234/host-catalogs/hc_1234/host-sets:create",
action: action.Create,
scope: "p_1234",
pin: "hc_1234",
resource: resource.HostSet,
},
{
name: "project scope, pinning id",
path: "/v1/orgs/o_abc123/projects/p_1234/host-catalogs/hc_1234/host-sets/hs_abc",
action: action.Read,
id: "hs_abc",
scope: "p_1234",
pin: "hc_1234",
resource: resource.HostSet,
},
{
name: "project scope, pinning id, custom action",
path: "/v1/orgs/o_abc123/projects/p_1234/host-catalogs/hc_1234/host-sets/hs_abc:update",
action: action.Update,
id: "hs_abc",
scope: "p_1234",
pin: "hc_1234",
resource: resource.HostSet,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
require, assert := require.New(t), assert.New(t)
if tc.method == "" {
tc.method = "GET"
}
req, err := http.NewRequest(tc.method, fmt.Sprintf("http://127.0.0.1:9200:%s", tc.path), nil)
require.NoError(err)
v := &verifier{
requestInfo: RequestInfo{
Path: req.URL.Path,
Method: tc.method,
},
}
err = v.parseAuthParams()
if tc.wantErrContains != "" {
require.Error(err)
assert.Contains(err.Error(), tc.wantErrContains, err.Error())
return
}
require.NoError(err)
if tc.path == "/" {
return
}
require.NotNil(v.res)
require.NotEqual(action.Unknown, v.act)
assert.Equal(tc.scope, v.res.ScopeId, "scope")
assert.Equal(tc.action, v.act, "action")
assert.Equal(tc.resource, v.res.Type, "type")
assert.Equal(tc.id, v.res.Id, "id")
assert.Equal(tc.pin, v.res.Pin, "pin")
})
}
}
+55 -296
View File
@@ -3,7 +3,6 @@ package controller
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
@@ -11,12 +10,14 @@ import (
"time"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/vault/internalshared/configutil"
"github.com/hashicorp/vault/sdk/helper/strutil"
"github.com/hashicorp/watchtower/api"
"github.com/hashicorp/watchtower/globals"
"github.com/hashicorp/watchtower/internal/auth"
"github.com/hashicorp/watchtower/internal/gen/controller/api/services"
"github.com/hashicorp/watchtower/internal/perms"
"github.com/hashicorp/watchtower/internal/servers/controller/handlers"
"github.com/hashicorp/watchtower/internal/servers/controller/handlers/authenticate"
"github.com/hashicorp/watchtower/internal/servers/controller/handlers/groups"
@@ -27,10 +28,6 @@ import (
"github.com/hashicorp/watchtower/internal/servers/controller/handlers/projects"
"github.com/hashicorp/watchtower/internal/servers/controller/handlers/roles"
"github.com/hashicorp/watchtower/internal/servers/controller/handlers/users"
"github.com/hashicorp/watchtower/internal/types/action"
"github.com/hashicorp/watchtower/internal/types/resource"
"github.com/hashicorp/watchtower/internal/types/scope"
"github.com/kr/pretty"
)
type HandlerProperties struct {
@@ -155,60 +152,21 @@ func wrapHandlerWithCommonFuncs(h http.Handler, c *Controller, props HandlerProp
ctx, cancelFunc := context.WithTimeout(r.Context(), maxRequestDuration)
defer cancelFunc()
userId := "u_anon"
var res *perms.Resource
var act action.Type
var err error
var authzResults *perms.ACLResults
if r.Method == http.MethodOptions {
// Don't perform authorization checking for preflight requests, at
// least for now. We could add it later if we wanted as an action on
// global or something but likely it would just be enabled/disabled
// per listener instead.
goto AUTHZ_FINISHED
}
// Perform authz checking
res, act, err = decorateAuthParams(r)
if err != nil {
c.logger.Trace("error reading auth parameters from URL", "url", r.URL.Path, "error", err)
// Maybe this isn't the best option, but a URL we can't parse from
// an auth perspective is probably just an invalid URL altogether.
// Treating it as a bad request can be perceived to be less leaky
// than a 404.
w.WriteHeader(http.StatusBadRequest)
return
}
// The resource is only nil with no error if the path is something
// unauthenticated, e.g. the UI serving path.
if res != nil {
authzResults, userId, err = c.performAuthzCheck(ctx, r, res, act)
if err != nil {
c.logger.Error("error during authz check", "error", err)
w.WriteHeader(http.StatusForbidden)
return
}
if userId == "" || !authzResults.Allowed {
// TODO: Decide whether to remove this
if disableAuthzFailures {
c.logger.Info("failed authz info for request", "resource", pretty.Sprint(res), "user_id", userId, "action", act.String())
} else {
w.WriteHeader(http.StatusForbidden)
return
}
}
}
AUTHZ_FINISHED:
// Add the user ID to the context
ctx = context.WithValue(ctx, globals.ContextUserIdValue, userId)
// Add a size limiter if desired
if maxRequestSize > 0 {
ctx = context.WithValue(ctx, "max_request_size", maxRequestSize)
}
ctx = context.WithValue(ctx, "original_request_path", r.URL.Path)
// Add values for authn/authz checking
requestInfo := auth.RequestInfo{
Path: r.URL.Path,
Method: r.Method,
DisableAuthzFailures: disableAuthzFailures,
}
requestInfo.PublicId, requestInfo.Token = getTokenFromRequest(c.logger, r)
ctx = auth.NewVerifierContext(ctx, c.logger, c.IamRepoFn, c.AuthTokenRepoFn, requestInfo)
// Set the context back on the request
r = r.WithContext(ctx)
h.ServeHTTP(w, r)
@@ -294,162 +252,6 @@ func wrapHandlerWithCors(h http.Handler, props HandlerProperties) http.Handler {
})
}
func decorateAuthParams(r *http.Request) (*perms.Resource, action.Type, error) {
if r == nil {
return nil, action.Unknown, errors.New("decorate auth params: incoming request is nil")
}
// Remove trailing and leading slashes
trimmedPath := strings.Trim(r.URL.Path, "/")
if !strings.HasPrefix(trimmedPath, "v1") {
// Don't look for auth params for requests to fetch the UI
return nil, action.Unknown, nil
}
splitPath := strings.Split(strings.TrimPrefix(trimmedPath, "v1"), "/")
splitLen := len(splitPath)
if splitLen == 0 {
return nil, action.Unknown, fmt.Errorf("decorate auth params: invalid path")
}
var act action.Type
var typStr string
scp := scope.Global
res := &perms.Resource{
ScopeId: scope.Global.String(),
}
// Handle non-custom types. We'll deal with custom types, including list,
// after parsing the path.
switch r.Method {
case "GET":
act = action.Read
case "POST":
act = action.Create
case "PATCH":
act = action.Update
case "DELETE":
act = action.Delete
default:
return nil, action.Unknown, fmt.Errorf("decorate auth params: unknown method %q", r.Method)
}
// Look for a custom action
colonSplit := strings.Split(splitPath[splitLen-1], ":")
switch len(colonSplit) {
case 1:
// No custom action specified
case 2:
actStr := colonSplit[len(colonSplit)-1]
act = action.Map[actStr]
if act == action.Unknown || act == action.All {
return nil, action.Unknown, fmt.Errorf("decorate auth params: unknown action %q", actStr)
}
// Keep going with the logic without the custom action
splitPath[splitLen-1] = colonSplit[0]
default:
return nil, action.Unknown, fmt.Errorf("decorate auth params: unexpected number of colons in last segment %q", colonSplit[len(colonSplit)-1])
}
// Walk backwards. As we walk backwards we look for scopes and figure out if
// we're operating on a resource or a collection. We also populate the pin.
// The rules for the pin are as follows:
//
// * If the last segment is a collection, the pin is the immediately
// preceding ID
//
// * If the last segment is an ID, the pin is the immediately preceding ID
// not including the last segment
//
// * If at the end of the logic the pin is the id of a scope ("global",
// "o_...", "p_...") then there is no pin. The scopes are already enclosing
// so a pin is redundant.
nextIdIsPin := true
for i := splitLen - 1; i >= 0; i-- {
segment := splitPath[i]
// Collections don't contain underscores; every resource ID does.
segmentIsCollection := !strings.Contains(segment, "_")
if !segmentIsCollection && i != splitLen-1 && nextIdIsPin {
res.Pin = segment
nextIdIsPin = false
}
// Update the scope. Set it to org only if it's at global (that way we
// don't override project with org). We have to check if it's one less
// than the length of the split because operating on the id of a scope
// is actually in the enclosing scope (since you're in the parent scope
// operating on a child scope).
switch segment {
case "projects":
if i < splitLen-2 {
scp = scope.Project
res.ScopeId = splitPath[i+1]
}
case "orgs":
if scp == scope.Global {
if i < splitLen-2 {
scp = scope.Org
res.ScopeId = splitPath[i+1]
}
}
}
if segment == "" {
// This could be the case if we have an action like
// /orgs/o_1234/projects/p_1234/:set-defaults to act on the project
// itself but within its own scope
continue
}
if typStr == "" {
// The resource check takes place inside the type check because if
// we've identified the type we have either already identified the
// right-most resource ID or we're operating on a collection, so
// this prevents us from finding a different ID earlier in the path.
//
// We continue on with the enclosing loop anyways though to ensure
// we find the right scope.
if res.Id == "" && !segmentIsCollection {
res.Id = segment
} else {
// Every collection is the plural of the resource type so drop
// the last 's'
if !strings.HasSuffix(segment, "s") {
return nil, action.Unknown, fmt.Errorf("decorate auth params: invalid collection syntax for %q", segment)
}
typStr = strings.TrimSuffix(segment, "s")
}
}
}
if typStr != "" {
res.Type = resource.Map[typStr]
if res.Type == resource.Unknown {
return nil, action.Unknown, fmt.Errorf("decorate auth params: unknown resource type %q", typStr)
}
} else if res.Id == "" {
return nil, action.Unknown, errors.New("decorate auth params: id and type both not found")
}
// If we're operating on a collection (that is, the ID is blank) and it's a
// GET, it's actually a list
if res.Id == "" && act == action.Read {
act = action.List
}
// If the pin ended up being a scope, nil it out
if res.Pin != "" {
if res.Pin == "global" ||
strings.HasPrefix(res.Pin, "o_") ||
strings.HasPrefix(res.Pin, "p_") {
res.Pin = ""
}
}
return res, act, nil
}
type tokenFormat int
const (
@@ -464,102 +266,59 @@ const (
jsVisibleCookieName = "wt-js-token-cookie"
)
func (c *Controller) performAuthzCheck(ctx context.Context, req *http.Request, res *perms.Resource, act action.Type) (*perms.ACLResults, string, error) {
userId := "u_anon"
if res == nil {
return nil, userId, errors.New("perform authz check: res is nil")
}
var receivedTokenType tokenFormat
var fullToken, token, publicId string
// getTokenFromRequest pulls the token from either the Authorization header or
// split cookies and parses it. If it cannot be parsed successfully, the issue
// is logged and we return blank, so logic will continue as the anonymous user.
// The public ID and token are returned
func getTokenFromRequest(logger hclog.Logger, req *http.Request) (string, string) {
// First, get the token, either from the authorization header or from split
// cookies
{
if authHeader := req.Header.Get("Authorization"); authHeader != "" {
headerSplit := strings.SplitN(strings.TrimSpace(authHeader), " ", 2)
if len(headerSplit) == 2 && strings.EqualFold(strings.TrimSpace(headerSplit[0]), "bearer") {
receivedTokenType = authTokenTypeBearer
fullToken = strings.TrimSpace(headerSplit[1])
}
var receivedTokenType tokenFormat
var fullToken string
if authHeader := req.Header.Get("Authorization"); authHeader != "" {
headerSplit := strings.SplitN(strings.TrimSpace(authHeader), " ", 2)
if len(headerSplit) == 2 && strings.EqualFold(strings.TrimSpace(headerSplit[0]), "bearer") {
receivedTokenType = authTokenTypeBearer
fullToken = strings.TrimSpace(headerSplit[1])
}
if receivedTokenType != authTokenTypeBearer {
var httpCookiePayload string
var jsCookiePayload string
if hc, err := req.Cookie(httpOnlyCookieName); err == nil {
httpCookiePayload = hc.Value
}
if jc, err := req.Cookie(jsVisibleCookieName); err == nil {
jsCookiePayload = jc.Value
}
if httpCookiePayload != "" && jsCookiePayload != "" {
receivedTokenType = authTokenTypeSplitCookie
fullToken = jsCookiePayload + httpCookiePayload
}
}
if receivedTokenType != authTokenTypeBearer {
var httpCookiePayload string
var jsCookiePayload string
if hc, err := req.Cookie(httpOnlyCookieName); err == nil {
httpCookiePayload = hc.Value
}
if receivedTokenType == authTokenTypeUnknown || fullToken == "" {
// We didn't find auth info or a client screwed up and put in a
// blank header instead of nothing at all, so carry on as the
// anonymous user
goto GRANTSLOOKUP
if jc, err := req.Cookie(jsVisibleCookieName); err == nil {
jsCookiePayload = jc.Value
}
splitFullToken := strings.Split(fullToken, "_")
if len(splitFullToken) != 3 {
return nil, userId, fmt.Errorf("perform authz check: unexpected number of segments in token, expected %d, found %d", 3, len(splitFullToken))
}
token = splitFullToken[2]
publicId = strings.Join(splitFullToken[0:2], "_")
if receivedTokenType == authTokenTypeUnknown || token == "" || publicId == "" {
return nil, userId, fmt.Errorf("perform authz check: after parsing, could not find valid token")
if httpCookiePayload != "" && jsCookiePayload != "" {
receivedTokenType = authTokenTypeSplitCookie
fullToken = jsCookiePayload + httpCookiePayload
}
}
// Validate the token and fetch the corresponding user ID
{
tokenRepo, err := c.AuthTokenRepoFn()
if err != nil {
return nil, userId, fmt.Errorf("perform authz check: failed to get authtoken repo: %w", err)
}
at, err := tokenRepo.ValidateToken(ctx, publicId, token)
if err != nil {
return nil, userId, fmt.Errorf("perform authz check: failed to validate token: %w", err)
}
if at != nil {
userId = at.GetIamUserId()
}
if receivedTokenType == authTokenTypeUnknown || fullToken == "" {
// We didn't find auth info or a client screwed up and put in a blank
// header instead of nothing at all, so return blank which will indicate
// the anonymouse user
return "", ""
}
GRANTSLOOKUP:
var parsedGrants []perms.Grant
var grantPairs []perms.GrantPair
// Fetch and parse grants for this user ID
{
iamRepo, err := c.IamRepoFn()
if err != nil {
return nil, userId, fmt.Errorf("perform authz check: failed to get iam repo: %w", err)
}
grantPairs, err = iamRepo.GrantsForUser(ctx, userId)
if err != nil {
return nil, userId, fmt.Errorf("perform authz check: failed to query for user grants: %w", err)
}
parsedGrants = make([]perms.Grant, 0, len(grantPairs))
for _, pair := range grantPairs {
parsed, err := perms.Parse(pair.ScopeId, userId, pair.Grant)
if err != nil {
return nil, userId, fmt.Errorf("perform authz check: failed to parse grant %#v: %w", pair.Grant, err)
}
parsedGrants = append(parsedGrants, parsed)
}
splitFullToken := strings.Split(fullToken, "_")
if len(splitFullToken) != 3 {
logger.Trace("get token from request: unexpected number of segments in token", "expected", 3, "found", len(splitFullToken))
return "", ""
}
acl := perms.NewACL(parsedGrants...)
allowed := acl.Allowed(*res, act)
return &allowed, userId, nil
token := splitFullToken[2]
publicId := strings.Join(splitFullToken[0:2], "_")
if receivedTokenType == authTokenTypeUnknown || token == "" || publicId == "" {
logger.Trace("get token from request: after parsing, could not find valid token")
return "", ""
}
return publicId, token
}
/*
+1 -221
View File
@@ -12,8 +12,6 @@ import (
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/hashicorp/watchtower/internal/gen/controller/api/services"
"github.com/hashicorp/watchtower/internal/types/action"
"github.com/hashicorp/watchtower/internal/types/resource"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -207,7 +205,7 @@ func TestHandleGrpcGateway(t *testing.T) {
{
"Non existent path",
"v1/this-is-made-ups",
http.StatusBadRequest,
http.StatusNotFound,
},
{
"Unimplemented path",
@@ -229,221 +227,3 @@ func TestHandleGrpcGateway(t *testing.T) {
})
}
}
func TestHandler_AuthDecoration(t *testing.T) {
cases := []struct {
name string
path string
method string
action action.Type
scope string
resource resource.Type
id string
pin string
wantErrContains string
}{
{
name: "global scope, read, with id",
path: "/v1/users/u_anon",
method: "GET",
action: action.Read,
scope: "global",
resource: resource.User,
id: "u_anon",
},
{
name: "global scope, update, with id",
path: "/v1/auth-methods/am_1234",
method: "PATCH",
action: action.Update,
scope: "global",
resource: resource.AuthMethod,
id: "am_1234",
},
{
name: "global scope, delete",
path: "/v1/orgs/o_1234",
method: "DELETE",
action: action.Delete,
scope: "global",
resource: resource.Org,
id: "o_1234",
},
{
name: "global scope, create",
path: "/v1/roles",
method: "POST",
action: action.Create,
scope: "global",
resource: resource.Role,
},
{
name: "global, invalid collection syntax",
path: "/v1/org",
wantErrContains: "invalid collection syntax",
},
{
name: "global, custom action",
path: "/v1/orgs/o_123/auth-methods/am_1234:authenticate",
method: "POST",
action: action.Authenticate,
scope: "o_123",
resource: resource.AuthMethod,
id: "am_1234",
},
{
name: "root, unknown action",
path: "/v1/:authentifake",
wantErrContains: "unknown action",
},
{
name: "root, unknown empty action",
path: "/v1/:",
wantErrContains: "unknown action",
},
{
name: "root, invalid method",
path: "/v1/:authenticate",
method: "FOOBAR",
wantErrContains: "unknown method",
},
{
name: "root, wrong number of colons",
path: "/v1/:auth:enticate",
wantErrContains: "unexpected number of colons",
},
{
name: "org scope, valid",
path: "/v1/orgs/o_abc123/auth-methods",
method: "POST",
action: action.Create,
scope: "o_abc123",
resource: resource.AuthMethod,
},
{
name: "project scope, valid",
path: "/v1/orgs/o_abc123/projects/p_1234/host-catalogs",
method: "POST",
action: action.Create,
scope: "p_1234",
resource: resource.HostCatalog,
},
{
name: "project scope, action on project",
path: "/v1/orgs/o_abc123/projects/p_1234/:set-principals",
method: "POST",
action: action.SetPrincipals,
scope: "p_1234",
resource: resource.Project,
id: "p_1234",
},
{
name: "org scope, action on project",
path: "/v1/orgs/o_abc123/projects/p_1234:set-principals",
method: "POST",
action: action.SetPrincipals,
scope: "o_abc123",
resource: resource.Project,
id: "p_1234",
},
{
name: "org scope, get on collection is list",
path: "/v1/orgs/o_abc123/projects",
action: action.List,
scope: "o_abc123",
resource: resource.Project,
},
{
name: "org scope, action on org",
path: "/v1/orgs/o_abc123/:deauthenticate",
action: action.Deauthenticate,
scope: "o_abc123",
resource: resource.Org,
id: "o_abc123",
},
{
name: "top level action, invalid",
path: "/v1/:read",
wantErrContains: "id and type both not found",
},
{
name: "top level, invalid",
path: "/v1/",
wantErrContains: "id and type both not found",
},
{
name: "non-api path",
path: "/",
},
{
name: "project scope, pinning collection",
path: "/v1/orgs/o_abc123/projects/p_1234/host-catalogs/hc_1234/host-sets",
action: action.List,
scope: "p_1234",
pin: "hc_1234",
resource: resource.HostSet,
},
{
name: "project scope, pinning collection, custom action",
path: "/v1/orgs/o_abc123/projects/p_1234/host-catalogs/hc_1234/host-sets:create",
action: action.Create,
scope: "p_1234",
pin: "hc_1234",
resource: resource.HostSet,
},
{
name: "project scope, pinning id",
path: "/v1/orgs/o_abc123/projects/p_1234/host-catalogs/hc_1234/host-sets/hs_abc",
action: action.Read,
id: "hs_abc",
scope: "p_1234",
pin: "hc_1234",
resource: resource.HostSet,
},
{
name: "project scope, pinning id, custom action",
path: "/v1/orgs/o_abc123/projects/p_1234/host-catalogs/hc_1234/host-sets/hs_abc:update",
action: action.Update,
id: "hs_abc",
scope: "p_1234",
pin: "hc_1234",
resource: resource.HostSet,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
require, assert := require.New(t), assert.New(t)
if tc.method == "" {
tc.method = "GET"
}
req, err := http.NewRequest(tc.method, fmt.Sprintf("http://127.0.0.1:9200:%s", tc.path), nil)
require.NoError(err)
res, act, err := decorateAuthParams(nil)
assert.Nil(res)
require.Error(err)
assert.Equal(action.Unknown, act)
assert.Contains(err.Error(), "incoming request is nil")
res, act, err = decorateAuthParams(req)
if tc.wantErrContains != "" {
require.Error(err)
assert.Contains(err.Error(), tc.wantErrContains, err.Error())
return
}
require.NoError(err)
if tc.path == "/" {
return
}
require.NotNil(res)
require.NotEqual(action.Unknown, act)
assert.Equal(tc.scope, res.ScopeId, "scope")
assert.Equal(tc.action, act, "action")
assert.Equal(tc.resource, res.Type, "type")
assert.Equal(tc.id, res.Id, "id")
assert.Equal(tc.pin, res.Pin, "pin")
})
}
}