package auth import ( "testing" "housecarl/internal/model" ) func TestPasswords(t *testing.T) { h, err := HashPassword("correct horse") if err != nil { t.Fatal(err) } if !CheckPassword(h, "correct horse") || CheckPassword(h, "wrong horse") || CheckPassword("", "") { t.Error("password check") } if _, err := HashPassword("short"); err == nil { t.Error("short password accepted") } } func TestTokens(t *testing.T) { tok, pid, hash := NewToken() gotPID, secret, err := ParseToken(tok) if err != nil || gotPID != pid || !CheckSecret(secret, hash) { t.Fatalf("token %q: %v", tok, err) } if _, _, err := ParseToken("jarl_abc_def"); err == nil { t.Error("a Jarl token was accepted") } } func TestPermissions(t *testing.T) { op := &model.User{Username: "op", Grants: Roles["operator"]} p := &Principal{User: op} if !p.Can(ResConfig, true) || !p.Can(ResAudit, false) || p.Can(ResAudit, true) || p.IsAdmin() { t.Error("operator") } admin := &model.User{Username: "admin", Admin: true} p = &Principal{User: admin, Token: &model.Token{Grants: []model.Grant{{Resource: ResLog, Access: Read}}}} if !p.Can(ResLog, false) || p.Can(ResLog, true) || p.Can(ResConfig, false) || p.IsAdmin() { t.Error("restricted admin token") } if !Narrower(Roles["log"], Roles["operator"]) || Narrower(Roles["operator"], Roles["viewer"]) { t.Error("narrower") } if _, err := ParseGrant("log"); err == nil { t.Error("grant without access accepted") } if g, err := ParseGrant("Config:Write"); err != nil || g.Resource != "config" { t.Errorf("grant %v %v", g, err) } } func TestSetGrants(t *testing.T) { g, err := ParseGrant("sets:write:guest-signed-in, portal") if err != nil || len(g.Sets) != 2 || FormatGrant(g) != "sets:write:guest-signed-in,portal" { t.Fatalf("parse %+v %v", g, err) } if _, err := ParseGrant("config:write:guest"); err == nil { t.Error("a config grant naming sets was accepted") } user := &model.User{Username: "portal", Grants: []model.Grant{g}} p := &Principal{User: user} if !p.CanSet("guest-signed-in", true) || !p.CanSet("PORTAL", false) || p.CanSet("trusted", false) || p.Can(ResConfig, false) { t.Error("set-scoped user") } admin := &Principal{User: &model.User{Username: "admin", Admin: true}, Token: &model.Token{Grants: []model.Grant{{Resource: ResSets, Access: Write, Sets: []string{"guest-signed-in"}}}}} if !admin.CanSet("guest-signed-in", true) || admin.CanSet("trusted", true) { t.Error("an admin's set-scoped token") } }