Skip to content

added user, exp, and allowed_paths #289

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jun 18, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

## [master](https://github.com/arangodb-helper/arangodb/tree/master) (N/A)
- Allow to pass environment variables to processes and standardize argument pass (--envs.<group>.<ENV>=<VALUE> and --args.<group>.<ARG>=<VALUE>)
- Extend JWT Generator functionality by additional fields

# ArangoDB Starter Changelog Before 0.15.0

Expand Down
83 changes: 79 additions & 4 deletions auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ package main
import (
"fmt"
"io/ioutil"
"strconv"
"strings"
"time"

"github.com/spf13/cobra"

Expand All @@ -34,9 +36,10 @@ import (

var (
cmdAuth = &cobra.Command{
Use: "auth",
Short: "ArangoDB authentication helper commands",
Run: cmdShowUsage,
Use: "auth",
Short: "ArangoDB authentication helper commands",
PersistentPreRunE: persistentAuthPreFunE,
Run: cmdShowUsage,
}
cmdAuthHeader = &cobra.Command{
Use: "header",
Expand All @@ -51,6 +54,12 @@ var (
authOptions struct {
jwtSecretFile string
user string
paths []string
exp string
expDuration time.Duration

fieldsOverride []string
fieldsOverrideMap map[string]interface{}
}
)

Expand All @@ -62,6 +71,9 @@ func init() {
pf := cmdAuth.PersistentFlags()
pf.StringVar(&authOptions.jwtSecretFile, "auth.jwt-secret", "", "name of a plain text file containing a JWT secret used for server authentication")
pf.StringVar(&authOptions.user, "auth.user", "", "name of a user to authenticate as. If empty, 'super-user' authentication is used")
pf.StringSliceVar(&authOptions.paths, "auth.paths", nil, "a list of allowed pathes. The path must not include the '_db/DBNAME' prefix.")
pf.StringVar(&authOptions.exp, "auth.exp", "", "a time in which token should expire - based on current time in UTC. Supported units: h, m, s (default)")
pf.StringSliceVar(&authOptions.fieldsOverride, "auth.fields", nil, "a list of additional fields set in the token. This flags override one auto-generated in token")
}

// mustAuthCreateJWTToken creates a the JWT token based on authentication options.
Expand All @@ -77,7 +89,7 @@ func mustAuthCreateJWTToken() string {
log.Fatal().Err(err).Msgf("Failed to read JWT secret file '%s'", authOptions.jwtSecretFile)
}
jwtSecret := strings.TrimSpace(string(content))
token, err := service.CreateJwtToken(jwtSecret, authOptions.user)
token, err := service.CreateJwtToken(jwtSecret, authOptions.user, "", authOptions.paths, authOptions.expDuration, authOptions.fieldsOverrideMap)
if err != nil {
log.Fatal().Err(err).Msg("Failed to create JWT token")
}
Expand All @@ -95,3 +107,66 @@ func cmdAuthTokenRun(cmd *cobra.Command, args []string) {
token := mustAuthCreateJWTToken()
fmt.Println(token)
}

func persistentAuthPreFunE(cmd *cobra.Command, args []string) error {
cmdMain.PersistentPreRun(cmd, args)

if authOptions.exp != "" {
d, err := durationParser(authOptions.exp, "s")
if err != nil {
return err
}

if d < 0 {
return fmt.Errorf("negative duration under --auth.exp is not allowed")
}

authOptions.expDuration = d
}

authOptions.fieldsOverrideMap = map[string]interface{}{}

for _, field := range authOptions.fieldsOverride {
tokens := strings.Split(field, "=")
if len(tokens) == 0 {
return fmt.Errorf("invalid format of the field override: `%s`", field)
}

key := tokens[0]
value := strings.Join(tokens[1:], "=")
var calculatedValue interface{} = value

switch value {
case "true":
calculatedValue = true
case "false":
calculatedValue = false
default:
if i, err := strconv.Atoi(value); err == nil {
calculatedValue = i
}
}

authOptions.fieldsOverrideMap[key] = calculatedValue
}

return nil
}

func durationParser(duration string, defaultUnit string) (time.Duration, error) {
if d, err := time.ParseDuration(duration); err == nil {
return d, nil
} else {
if !strings.HasPrefix(err.Error(), "time: missing unit in duration ") {
return 0, err
}

duration = fmt.Sprintf("%s%s", duration, defaultUnit)

if d, err := time.ParseDuration(duration); err == nil {
return d, nil
} else {
return 0, err
}
}
}
47 changes: 47 additions & 0 deletions auth_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
//
// DISCLAIMER
//
// Copyright 2021 ArangoDB GmbH, Cologne, Germany
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Copyright holder is ArangoDB GmbH, Cologne, Germany
//
// Author Adam Janikowski
//

package main

import (
"testing"

"github.com/stretchr/testify/require"
)

func parseDuration(t *testing.T, in, out string) {
t.Run(in, func(t *testing.T) {
v, err := durationParser(in, "s")
require.NoError(t, err)

s := v.String()

require.Equal(t, out, s)
})
}

func Test_Auth_DurationTest(t *testing.T) {
parseDuration(t, "5", "5s")
parseDuration(t, "5s", "5s")
parseDuration(t, "5m", "5m0s")
parseDuration(t, "5h", "5h0m0s")
}
22 changes: 19 additions & 3 deletions service/authentication.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ package service

import (
"net/http"
"time"

jwt "github.com/dgrijalva/jwt-go"
)
Expand All @@ -35,19 +36,34 @@ const (

// CreateJwtToken calculates a JWT authorization token based on the given secret.
// If the secret is empty, an empty token is returned.
func CreateJwtToken(jwtSecret, user string) (string, error) {
func CreateJwtToken(jwtSecret, user string, serverId string, paths []string, exp time.Duration, fieldsOverride jwt.MapClaims) (string, error) {
if jwtSecret == "" {
return "", nil
}
if serverId == "" {
serverId = "foo"
}

// Create a new token object, specifying signing method and the claims
// you would like it to contain.
claims := jwt.MapClaims{
"iss": "arangodb",
"server_id": "foo",
"server_id": serverId,
}
if user != "" {
claims["preferred_username"] = user
}
if paths != nil {
claims["allowed_paths"] = paths
}
if exp > 0 {
t := time.Now().UTC()
claims["iat"] = t.Unix()
claims["exp"] = t.Add(exp).Unix()
}
for k, v := range fieldsOverride {
claims[k] = v
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

// Sign and get the complete encoded token as a string using the secret
Expand All @@ -66,7 +82,7 @@ func addJwtHeader(req *http.Request, jwtSecret string) error {
if jwtSecret == "" {
return nil
}
signedToken, err := CreateJwtToken(jwtSecret, "")
signedToken, err := CreateJwtToken(jwtSecret, "", "", nil, 0, nil)
if err != nil {
return maskAny(err)
}
Expand Down