Merge branch 'develop' of github.com:Budibase/budibase into feature/multi-tenants

This commit is contained in:
mike12345567 2021-07-20 15:56:12 +01:00
commit 129ff3fef2
48 changed files with 5481 additions and 193 deletions

View File

@ -5,6 +5,10 @@
"main": "src/index.js",
"author": "Budibase",
"license": "AGPL-3.0",
"scripts": {
"test": "jest",
"test:watch": "jest --watchAll"
},
"dependencies": {
"aws-sdk": "^2.901.0",
"bcryptjs": "^2.4.3",
@ -13,6 +17,7 @@
"koa-passport": "^4.1.4",
"lodash": "^4.17.21",
"node-fetch": "^2.6.1",
"@techpass/passport-openidconnect": "^0.3.0",
"passport-google-auth": "^1.0.2",
"passport-google-oauth": "^2.0.0",
"passport-jwt": "^4.0.0",
@ -22,8 +27,17 @@
"uuid": "^8.3.2",
"zlib": "^1.0.5"
},
"jest": {
"setupFiles": [
"./scripts/jestSetup.js"
]
},
"devDependencies": {
"ioredis-mock": "^5.5.5"
"ioredis-mock": "^5.5.5",
"jest": "^26.6.3",
"pouchdb-adapter-memory": "^7.2.2",
"pouchdb": "^7.2.1",
"pouchdb-all-dbs": "^1.0.2"
},
"gitHead": "d1836a898cab3f8ab80ee6d8f42be1a9eed7dcdc"
}

View File

@ -0,0 +1,5 @@
const env = require("../src/environment")
env._set("NODE_ENV", "jest")
env._set("JWT_SECRET", "test-jwtsecret")
env._set("LOG_LEVEL", "silent")

View File

@ -6,6 +6,7 @@ exports.UserStatus = {
exports.Cookies = {
CurrentApp: "budibase:currentapp",
Auth: "budibase:auth",
OIDC_CONFIG: "budibase:oidc:config",
}
exports.GlobalRoles = {
@ -20,6 +21,8 @@ exports.Configs = {
ACCOUNT: "account",
SMTP: "smtp",
GOOGLE: "google",
OIDC: "oidc",
OIDC_LOGOS: "logos_oidc",
}
exports.DEFAULT_TENANT_ID = "default"

View File

@ -86,7 +86,8 @@ exports.getGlobalDB = tenantId => {
*/
exports.getGlobalDBFromCtx = ctx => {
const user = ctx.user || {}
return exports.getGlobalDB(user.tenantId)
const params = ctx.request.params || {}
return exports.getGlobalDB(user.tenantId || params.tenantId)
}
/**

View File

@ -17,4 +17,8 @@ module.exports = {
MINIO_URL: process.env.MINIO_URL,
INTERNAL_API_KEY: process.env.INTERNAL_API_KEY,
isTest,
_set(key, value) {
process.env[key] = value
module.exports[key] = value
},
}

View File

@ -2,7 +2,14 @@ const passport = require("koa-passport")
const LocalStrategy = require("passport-local").Strategy
const JwtStrategy = require("passport-jwt").Strategy
const { getGlobalDB, StaticDatabases } = require("./db/utils")
const { jwt, local, authenticated, google, auditLog } = require("./middleware")
const {
jwt,
local,
authenticated,
google,
oidc,
auditLog,
} = require("./middleware")
const { setDB } = require("./db")
const userCache = require("./cache/user")
@ -45,6 +52,7 @@ module.exports = {
buildAuthMiddleware: authenticated,
passport,
google,
oidc,
jwt: require("jsonwebtoken"),
auditLog,
},

View File

@ -1,11 +1,13 @@
const jwt = require("./passport/jwt")
const local = require("./passport/local")
const google = require("./passport/google")
const oidc = require("./passport/oidc")
const authenticated = require("./authenticated")
const auditLog = require("./auditLog")
module.exports = {
google,
oidc,
jwt,
local,
authenticated,

View File

@ -1,77 +1,25 @@
const env = require("../../environment")
const jwt = require("jsonwebtoken")
const GoogleStrategy = require("passport-google-oauth").OAuth2Strategy
const {
generateGlobalUserID,
getGlobalDB,
ViewNames,
} = require("../../db/utils")
const { newid } = require("../../hashing")
const { createASession } = require("../../security/sessions")
const { lookupTenantId } = require("../../utils")
async function authenticate(token, tokenSecret, profile, done) {
// Check the user exists in the instance DB by email
const userId = generateGlobalUserID(profile.id)
const tenantId = await lookupTenantId(userId)
const db = getGlobalDB(tenantId)
const { authenticateThirdParty } = require("./third-party-common")
let dbUser
try {
// use the google profile id
dbUser = await db.get(userId)
} catch (err) {
const user = {
_id: userId,
provider: profile.provider,
roles: {},
...profile._json,
}
// check if an account with the google email address exists locally
const users = await db.query(`database/${ViewNames.USER_BY_EMAIL}`, {
key: profile._json.email,
include_docs: true,
})
// Google user already exists by email
if (users.rows.length > 0) {
const existing = users.rows[0].doc
// remove the local account to avoid conflicts
await db.remove(existing._id, existing._rev)
// merge with existing account
user.roles = existing.roles
user.builder = existing.builder
user.admin = existing.admin
const response = await db.post(user)
dbUser = user
dbUser._rev = response.rev
} else {
return done(
new Error(
"email does not yet exist. You must set up your local budibase account first."
),
false
)
}
async function authenticate(accessToken, refreshToken, profile, done) {
const thirdPartyUser = {
provider: profile.provider, // should always be 'google'
providerType: "google",
userId: profile.id,
profile: profile,
email: profile._json.email,
oauth2: {
accessToken: accessToken,
refreshToken: refreshToken,
},
}
// authenticate
const sessionId = newid()
await createASession(dbUser._id, { sessionId, tenantId: dbUser.tenantId })
dbUser.token = jwt.sign(
{
userId: dbUser._id,
sessionId,
},
env.JWT_SECRET
return authenticateThirdParty(
thirdPartyUser,
true, // require local accounts to exist
done
)
return done(null, dbUser)
}
/**
@ -102,3 +50,5 @@ exports.strategyFactory = async function (config) {
throw new Error("Error constructing google authentication strategy", err)
}
}
// expose for testing
exports.authenticate = authenticate

View File

@ -1,5 +1,6 @@
const { Cookies } = require("../../constants")
const env = require("../../environment")
const { authError } = require("./utils")
exports.options = {
secretOrKey: env.JWT_SECRET,
@ -12,6 +13,6 @@ exports.authenticate = async function (jwt, done) {
try {
return done(null, jwt)
} catch (err) {
return done(new Error("JWT invalid."), false)
return authError(done, "JWT invalid", err)
}
}

View File

@ -3,6 +3,7 @@ const { UserStatus, DEFAULT_TENANT_ID } = require("../../constants")
const { compare } = require("../../hashing")
const env = require("../../environment")
const { getGlobalUserByEmail } = require("../../utils")
const { authError } = require("./utils")
const { newid } = require("../../hashing")
const { createASession } = require("../../security/sessions")
@ -21,20 +22,20 @@ exports.options = {
* @returns The authenticated user, or errors if they occur
*/
exports.authenticate = async function (ctx, email, password, done) {
if (!email) return done(null, false, "Email Required.")
if (!password) return done(null, false, "Password Required.")
if (!email) return authError(done, "Email Required")
if (!password) return authError(done, "Password Required")
const params = ctx.params || {}
// use the request to find the tenantId
let tenantId = params.tenantId || DEFAULT_TENANT_ID
const dbUser = await getGlobalUserByEmail(email, tenantId)
if (dbUser == null) {
return done(null, false, { message: "User not found" })
return authError(done, "User not found")
}
// check that the user is currently inactive, if this is the case throw invalid
if (dbUser.status === UserStatus.INACTIVE) {
return done(null, false, { message: INVALID_ERR })
return authError(done, INVALID_ERR)
}
// authenticate
@ -55,6 +56,6 @@ exports.authenticate = async function (ctx, email, password, done) {
return done(null, dbUser)
} else {
done(new Error(INVALID_ERR), false)
return authError(done, INVALID_ERR)
}
}

View File

@ -0,0 +1,128 @@
const fetch = require("node-fetch")
const OIDCStrategy = require("@techpass/passport-openidconnect").Strategy
const { authenticateThirdParty } = require("./third-party-common")
/**
* @param {*} issuer The identity provider base URL
* @param {*} sub The user ID
* @param {*} profile The user profile information. Created by passport from the /userinfo response
* @param {*} jwtClaims The parsed id_token claims
* @param {*} accessToken The access_token for contacting the identity provider - may or may not be a JWT
* @param {*} refreshToken The refresh_token for obtaining a new access_token - usually not a JWT
* @param {*} idToken The id_token - always a JWT
* @param {*} params The response body from requesting an access_token
* @param {*} done The passport callback: err, user, info
*/
async function authenticate(
issuer,
sub,
profile,
jwtClaims,
accessToken,
refreshToken,
idToken,
params,
done
) {
const thirdPartyUser = {
// store the issuer info to enable sync in future
provider: issuer,
providerType: "oidc",
userId: profile.id,
profile: profile,
email: getEmail(profile, jwtClaims),
oauth2: {
accessToken: accessToken,
refreshToken: refreshToken,
},
}
return authenticateThirdParty(
thirdPartyUser,
false, // don't require local accounts to exist
done
)
}
/**
* @param {*} profile The structured profile created by passport using the user info endpoint
* @param {*} jwtClaims The claims returned in the id token
*/
function getEmail(profile, jwtClaims) {
// profile not guaranteed to contain email e.g. github connected azure ad account
if (profile._json.email) {
return profile._json.email
}
// fallback to id token email
if (jwtClaims.email) {
return jwtClaims.email
}
// fallback to id token preferred username
const username = jwtClaims.preferred_username
if (username && validEmail(username)) {
return username
}
throw new Error(
`Could not determine user email from profile ${JSON.stringify(
profile
)} and claims ${JSON.stringify(jwtClaims)}`
)
}
function validEmail(value) {
return (
value &&
!!value.match(
/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
)
)
}
/**
* Create an instance of the oidc passport strategy. This wrapper fetches the configuration
* from couchDB rather than environment variables, using this factory is necessary for dynamically configuring passport.
* @returns Dynamically configured Passport OIDC Strategy
*/
exports.strategyFactory = async function (config, callbackUrl) {
try {
const { clientID, clientSecret, configUrl } = config
if (!clientID || !clientSecret || !callbackUrl || !configUrl) {
throw new Error(
"Configuration invalid. Must contain clientID, clientSecret, callbackUrl and configUrl"
)
}
const response = await fetch(configUrl)
if (!response.ok) {
throw new Error(
`Unexpected response when fetching openid-configuration: ${response.statusText}`
)
}
const body = await response.json()
return new OIDCStrategy(
{
issuer: body.issuer,
authorizationURL: body.authorization_endpoint,
tokenURL: body.token_endpoint,
userInfoURL: body.userinfo_endpoint,
clientID: clientID,
clientSecret: clientSecret,
callbackURL: callbackUrl,
},
authenticate
)
} catch (err) {
console.error(err)
throw new Error("Error constructing OIDC authentication strategy", err)
}
}
// expose for testing
exports.authenticate = authenticate

View File

@ -0,0 +1,74 @@
// Mock data
const { data } = require("./utilities/mock-data")
const googleConfig = {
callbackURL: "http://somecallbackurl",
clientID: data.clientID,
clientSecret: data.clientSecret,
}
const profile = {
id: "mockId",
_json: {
email : data.email
},
provider: "google"
}
const user = data.buildThirdPartyUser("google", "google", profile)
describe("google", () => {
describe("strategyFactory", () => {
// mock passport strategy factory
jest.mock("passport-google-oauth")
const mockStrategy = require("passport-google-oauth").OAuth2Strategy
it("should create successfully create a google strategy", async () => {
const google = require("../google")
await google.strategyFactory(googleConfig)
const expectedOptions = {
clientID: googleConfig.clientID,
clientSecret: googleConfig.clientSecret,
callbackURL: googleConfig.callbackURL,
}
expect(mockStrategy).toHaveBeenCalledWith(
expectedOptions,
expect.anything()
)
})
})
describe("authenticate", () => {
afterEach(() => {
jest.clearAllMocks();
});
// mock third party common authentication
jest.mock("../third-party-common")
const authenticateThirdParty = require("../third-party-common").authenticateThirdParty
// mock the passport callback
const mockDone = jest.fn()
it("delegates authentication to third party common", async () => {
const google = require("../google")
await google.authenticate(
data.accessToken,
data.refreshToken,
profile,
mockDone
)
expect(authenticateThirdParty).toHaveBeenCalledWith(
user,
true,
mockDone)
})
})
})

View File

@ -0,0 +1,143 @@
// Mock data
const { data } = require("./utilities/mock-data")
const issuer = "mockIssuer"
const sub = "mockSub"
const profile = {
id: "mockId",
_json: {
email : data.email
}
}
let jwtClaims = {}
const idToken = "mockIdToken"
const params = {}
const callbackUrl = "http://somecallbackurl"
// response from .well-known/openid-configuration
const oidcConfigUrlResponse = {
issuer: issuer,
authorization_endpoint: "mockAuthorizationEndpoint",
token_endpoint: "mockTokenEndpoint",
userinfo_endpoint: "mockUserInfoEndpoint"
}
const oidcConfig = {
configUrl: "http://someconfigurl",
clientID: data.clientID,
clientSecret: data.clientSecret,
}
const user = data.buildThirdPartyUser(issuer, "oidc", profile)
describe("oidc", () => {
describe("strategyFactory", () => {
// mock passport strategy factory
jest.mock("@techpass/passport-openidconnect")
const mockStrategy = require("@techpass/passport-openidconnect").Strategy
// mock the request to retrieve the oidc configuration
jest.mock("node-fetch")
const mockFetch = require("node-fetch")
mockFetch.mockReturnValue({
ok: true,
json: () => oidcConfigUrlResponse
})
it("should create successfully create an oidc strategy", async () => {
const oidc = require("../oidc")
await oidc.strategyFactory(oidcConfig, callbackUrl)
expect(mockFetch).toHaveBeenCalledWith(oidcConfig.configUrl)
const expectedOptions = {
issuer: oidcConfigUrlResponse.issuer,
authorizationURL: oidcConfigUrlResponse.authorization_endpoint,
tokenURL: oidcConfigUrlResponse.token_endpoint,
userInfoURL: oidcConfigUrlResponse.userinfo_endpoint,
clientID: oidcConfig.clientID,
clientSecret: oidcConfig.clientSecret,
callbackURL: callbackUrl,
}
expect(mockStrategy).toHaveBeenCalledWith(
expectedOptions,
expect.anything()
)
})
})
describe("authenticate", () => {
afterEach(() => {
jest.clearAllMocks();
});
// mock third party common authentication
jest.mock("../third-party-common")
const authenticateThirdParty = require("../third-party-common").authenticateThirdParty
// mock the passport callback
const mockDone = jest.fn()
async function doAuthenticate() {
const oidc = require("../oidc")
await oidc.authenticate(
issuer,
sub,
profile,
jwtClaims,
data.accessToken,
data.refreshToken,
idToken,
params,
mockDone
)
}
async function doTest() {
await doAuthenticate()
expect(authenticateThirdParty).toHaveBeenCalledWith(
user,
false,
mockDone)
}
it("delegates authentication to third party common", async () => {
doTest()
})
it("uses JWT email to get email", async () => {
delete profile._json.email
jwtClaims = {
email : "mock@budibase.com"
}
doTest()
})
it("uses JWT username to get email", async () => {
delete profile._json.email
jwtClaims = {
preferred_username : "mock@budibase.com"
}
doTest()
})
it("uses JWT invalid username to get email", async () => {
delete profile._json.email
jwtClaims = {
preferred_username : "invalidUsername"
}
await expect(doAuthenticate()).rejects.toThrow("Could not determine user email from profile");
})
})
})

View File

@ -0,0 +1,152 @@
// Mock data
require("./utilities/test-config")
const database = require("../../../db")
const { authenticateThirdParty } = require("../third-party-common")
const { data } = require("./utilities/mock-data")
const {
StaticDatabases,
generateGlobalUserID
} = require("../../../db/utils")
const { newid } = require("../../../hashing")
let db
const done = jest.fn()
const getErrorMessage = () => {
return done.mock.calls[0][2].message
}
describe("third party common", () => {
describe("authenticateThirdParty", () => {
let thirdPartyUser
beforeEach(() => {
db = database.getDB(StaticDatabases.GLOBAL.name)
thirdPartyUser = data.buildThirdPartyUser()
})
afterEach(async () => {
jest.clearAllMocks()
await db.destroy()
})
describe("validation", () => {
const testValidation = async (message) => {
await authenticateThirdParty(thirdPartyUser, false, done)
expect(done.mock.calls.length).toBe(1)
expect(getErrorMessage()).toContain(message)
}
it("provider fails", async () => {
delete thirdPartyUser.provider
testValidation("third party user provider required")
})
it("user id fails", async () => {
delete thirdPartyUser.userId
testValidation("third party user id required")
})
it("email fails", async () => {
delete thirdPartyUser.email
testValidation("third party user email required")
})
})
const expectUserIsAuthenticated = () => {
const user = done.mock.calls[0][1]
expect(user).toBeDefined()
expect(user._id).toBeDefined()
expect(user._rev).toBeDefined()
expect(user.token).toBeDefined()
return user
}
const expectUserIsSynced = (user, thirdPartyUser) => {
expect(user.provider).toBe(thirdPartyUser.provider)
expect(user.email).toBe(thirdPartyUser.email)
expect(user.firstName).toBe(thirdPartyUser.profile.name.givenName)
expect(user.lastName).toBe(thirdPartyUser.profile.name.familyName)
expect(user.thirdPartyProfile).toStrictEqual(thirdPartyUser.profile._json)
expect(user.oauth2).toStrictEqual(thirdPartyUser.oauth2)
}
describe("when the user doesn't exist", () => {
describe("when a local account is required", () => {
it("returns an error message", async () => {
await authenticateThirdParty(thirdPartyUser, true, done)
expect(done.mock.calls.length).toBe(1)
expect(getErrorMessage()).toContain("Email does not yet exist. You must set up your local budibase account first.")
})
})
describe("when a local account isn't required", () => {
it("creates and authenticates the user", async () => {
await authenticateThirdParty(thirdPartyUser, false, done)
const user = expectUserIsAuthenticated()
expectUserIsSynced(user, thirdPartyUser)
expect(user.roles).toStrictEqual({})
})
})
})
describe("when the user exists", () => {
let dbUser
let id
let email
const createUser = async () => {
dbUser = {
_id: id,
email: email,
}
const response = await db.post(dbUser)
dbUser._rev = response.rev
}
const expectUserIsUpdated = (user) => {
// id is unchanged
expect(user._id).toBe(id)
// user is updated
expect(user._rev).not.toBe(dbUser._rev)
}
describe("exists by email", () => {
beforeEach(async () => {
id = generateGlobalUserID(newid()) // random id
email = thirdPartyUser.email // matching email
await createUser()
})
it("syncs and authenticates the user", async () => {
await authenticateThirdParty(thirdPartyUser, true, done)
const user = expectUserIsAuthenticated()
expectUserIsSynced(user, thirdPartyUser)
expectUserIsUpdated(user)
})
})
describe("exists by id", () => {
beforeEach(async () => {
id = generateGlobalUserID(thirdPartyUser.userId) // matching id
email = "test@test.com" // random email
await createUser()
})
it("syncs and authenticates the user", async () => {
await authenticateThirdParty(thirdPartyUser, true, done)
const user = expectUserIsAuthenticated()
expectUserIsSynced(user, thirdPartyUser)
expectUserIsUpdated(user)
})
})
})
})
})

View File

@ -0,0 +1,20 @@
const PouchDB = require("pouchdb")
const allDbs = require("pouchdb-all-dbs")
const env = require("../../../../environment")
let POUCH_DB_DEFAULTS
// should always be test but good to do the sanity check
if (env.isTest()) {
PouchDB.plugin(require("pouchdb-adapter-memory"))
POUCH_DB_DEFAULTS = {
prefix: undefined,
adapter: "memory",
}
}
const Pouch = PouchDB.defaults(POUCH_DB_DEFAULTS)
allDbs(Pouch)
module.exports = Pouch

View File

@ -0,0 +1,54 @@
// Mock Data
const mockClientID = "mockClientID"
const mockClientSecret = "mockClientSecret"
const mockEmail = "mock@budibase.com"
const mockAccessToken = "mockAccessToken"
const mockRefreshToken = "mockRefreshToken"
const mockProvider = "mockProvider"
const mockProviderType = "mockProviderType"
const mockProfile = {
id: "mockId",
name: {
givenName: "mockGivenName",
familyName: "mockFamilyName",
},
_json: {
email: mockEmail,
},
}
const buildOauth2 = (
accessToken = mockAccessToken,
refreshToken = mockRefreshToken
) => ({
accessToken: accessToken,
refreshToken: refreshToken,
})
const buildThirdPartyUser = (
provider = mockProvider,
providerType = mockProviderType,
profile = mockProfile,
email = mockEmail,
oauth2 = buildOauth2()
) => ({
provider: provider,
providerType: providerType,
userId: profile.id,
profile: profile,
email: email,
oauth2: oauth2,
})
exports.data = {
clientID: mockClientID,
clientSecret: mockClientSecret,
email: mockEmail,
accessToken: mockAccessToken,
refreshToken: mockRefreshToken,
buildThirdPartyUser,
}

View File

@ -0,0 +1,3 @@
const packageConfiguration = require("../../../../index")
const CouchDB = require("./db")
packageConfiguration.init(CouchDB)

View File

@ -0,0 +1,131 @@
const env = require("../../environment")
const jwt = require("jsonwebtoken")
const { generateGlobalUserID, getGlobalDB } = require("../../db/utils")
const { authError } = require("./utils")
const { newid } = require("../../hashing")
const { createASession } = require("../../security/sessions")
const { getGlobalUserByEmail, lookupTenantId } = require("../../utils")
/**
* Common authentication logic for third parties. e.g. OAuth, OIDC.
*/
exports.authenticateThirdParty = async function (
thirdPartyUser,
requireLocalAccount = true,
done
) {
if (!thirdPartyUser.provider) {
return authError(done, "third party user provider required")
}
if (!thirdPartyUser.userId) {
return authError(done, "third party user id required")
}
if (!thirdPartyUser.email) {
return authError(done, "third party user email required")
}
// use the third party id
const userId = generateGlobalUserID(thirdPartyUser.userId)
const tenantId = await lookupTenantId(userId)
const db = getGlobalDB(tenantId)
let dbUser
// try to load by id
try {
dbUser = await db.get(userId)
} catch (err) {
// abort when not 404 error
if (!err.status || err.status !== 404) {
return authError(
done,
"Unexpected error when retrieving existing user",
err
)
}
}
// fallback to loading by email
if (!dbUser) {
dbUser = await getGlobalUserByEmail(thirdPartyUser.email, tenantId)
}
// exit early if there is still no user and auto creation is disabled
if (!dbUser && requireLocalAccount) {
return authError(
done,
"Email does not yet exist. You must set up your local budibase account first."
)
}
// first time creation
if (!dbUser) {
// setup a blank user using the third party id
dbUser = {
_id: userId,
roles: {},
}
}
dbUser = syncUser(dbUser, thirdPartyUser)
// create or sync the user
const response = await db.post(dbUser)
dbUser._rev = response.rev
// authenticate
const sessionId = newid()
await createASession(dbUser._id, { sessionId, tenantId })
dbUser.token = jwt.sign(
{
userId: dbUser._id,
sessionId,
},
env.JWT_SECRET
)
return done(null, dbUser)
}
/**
* @returns a user that has been sync'd with third party information
*/
function syncUser(user, thirdPartyUser) {
// provider
user.provider = thirdPartyUser.provider
user.providerType = thirdPartyUser.providerType
// email
user.email = thirdPartyUser.email
if (thirdPartyUser.profile) {
const profile = thirdPartyUser.profile
if (profile.name) {
const name = profile.name
// first name
if (name.givenName) {
user.firstName = name.givenName
}
// last name
if (name.familyName) {
user.lastName = name.familyName
}
}
// profile
user.thirdPartyProfile = {
...profile._json,
}
}
// oauth tokens for future use
if (thirdPartyUser.oauth2) {
user.oauth2 = {
...thirdPartyUser.oauth2,
}
}
return user
}

View File

@ -0,0 +1,14 @@
/**
* Utility to handle authentication errors.
*
* @param {*} done The passport callback.
* @param {*} message Message that will be returned in the response body
* @param {*} err (Optional) error that will be logged
*/
exports.authError = function (done, message, err = null) {
return done(
err,
null, // never return a user
{ message: message }
)
}

File diff suppressed because it is too large Load Diff

View File

@ -10,6 +10,7 @@
export let disabled = false
export let error = null
export let fieldText = ""
export let fieldIcon = ""
export let isPlaceholder = false
export let placeholderOption = null
export let options = []
@ -17,11 +18,11 @@
export let onSelectOption = () => {}
export let getOptionLabel = option => option
export let getOptionValue = option => option
export let getOptionIcon = null
export let open = false
export let readonly = false
export let quiet = false
export let autoWidth = false
const dispatch = createEventDispatcher()
const onClick = () => {
dispatch("click")
@ -42,6 +43,12 @@
aria-haspopup="listbox"
on:mousedown={onClick}
>
{#if fieldIcon}
<span class="icon-Placeholder-Padding">
<img src={fieldIcon} alt="Picker Icon" width="20" height="15" />
</span>
{/if}
<span
class="spectrum-Picker-label"
class:is-placeholder={isPlaceholder}
@ -104,6 +111,16 @@
tabindex="0"
on:click={() => onSelectOption(getOptionValue(option, idx))}
>
{#if getOptionIcon(option, idx)}
<span class="icon-Padding">
<img
src={getOptionIcon(option, idx)}
alt="test"
width="20"
height="15"
/>
</span>
{/if}
<span class="spectrum-Menu-itemLabel"
>{getOptionLabel(option, idx)}</span
>
@ -148,4 +165,12 @@
.spectrum-Picker-label.auto-width.is-placeholder {
padding-right: 2px;
}
.icon-Padding {
padding-right: 10px;
}
.icon-Placeholder-Padding {
padding-top: 5px;
padding-right: 10px;
}
</style>

View File

@ -10,6 +10,7 @@
export let options = []
export let getOptionLabel = option => option
export let getOptionValue = option => option
export let getOptionIcon = null
export let readonly = false
export let quiet = false
export let autoWidth = false
@ -17,6 +18,7 @@
const dispatch = createEventDispatcher()
let open = false
$: fieldText = getFieldText(value, options, placeholder)
$: fieldIcon = getFieldIcon(value, options, placeholder)
const getFieldText = (value, options, placeholder) => {
// Always use placeholder if no value
@ -36,6 +38,17 @@
return index !== -1 ? getOptionLabel(options[index], index) : value
}
const getFieldIcon = (value, options) => {
// Wait for options to load if there is a value but no options
if (!options?.length) {
return ""
}
const index = options.findIndex(
(option, idx) => getOptionValue(option, idx) === value
)
return index !== -1 ? getOptionIcon(options[index], index) : null
}
const selectOption = value => {
dispatch("change", value)
open = false
@ -55,6 +68,8 @@
{autoWidth}
{getOptionLabel}
{getOptionValue}
{getOptionIcon}
{fieldIcon}
isPlaceholder={value == null || value === ""}
placeholderOption={placeholder}
isOptionSelected={option => option === value}

View File

@ -13,6 +13,7 @@
export let options = []
export let getOptionLabel = option => extractProperty(option, "label")
export let getOptionValue = option => extractProperty(option, "value")
export let getOptionIcon = option => option?.icon
export let quiet = false
export let autoWidth = false
@ -21,6 +22,7 @@
value = e.detail
dispatch("change", e.detail)
}
const extractProperty = (value, property) => {
if (value && typeof value === "object") {
return value[property]
@ -41,6 +43,7 @@
{autoWidth}
{getOptionLabel}
{getOptionValue}
{getOptionIcon}
on:change={onChange}
on:click
/>

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.2 KiB

View File

@ -12,7 +12,7 @@
apps: "Create your first app",
smtp: "Set up email",
adminUser: "Create your first user",
oauth: "Set up OAuth",
sso: "Set up single sign-on",
}
</script>

View File

@ -1,12 +1,12 @@
<script>
import { ActionButton } from "@budibase/bbui"
import GoogleLogo from "assets/google-logo.png"
import { admin, auth } from "stores/portal"
import { admin, auth, organisation } from "stores/portal"
let show = false
$: show = $admin.checklist?.oauth
$: tenantId = $auth.tenantId
$: show = $organisation.google
</script>
{#if show}

View File

@ -0,0 +1,59 @@
<script>
import { ActionButton } from "@budibase/bbui"
import OidcLogo from "assets/oidc-logo.png"
import Auth0Logo from "assets/auth0-logo.png"
import MicrosoftLogo from "assets/microsoft-logo.png"
import OktaLogo from "assets/okta-logo.png"
import OneLoginLogo from "assets/onelogin-logo.png"
import { oidc, organisation } from "stores/portal"
import { onMount } from "svelte"
$: show = $organisation.oidc
let preDefinedIcons = {
Oidc: OidcLogo,
Auth0: Auth0Logo,
Microsoft: MicrosoftLogo,
Okta: OktaLogo,
OneLogin: OneLoginLogo,
}
onMount(async () => {
await oidc.init()
})
$: src = !$oidc.logo
? OidcLogo
: preDefinedIcons[$oidc.logo] || `/global/logos_oidc/${$oidc.logo}`
</script>
{#if show}
<ActionButton
on:click={() =>
window.open(`/api/admin/auth/oidc/configs/${$oidc.uuid}`, "_blank")}
>
<div class="inner">
<img {src} alt="oidc icon" />
<p>{`Sign in with ${$oidc.name || "OIDC"}`}</p>
</div>
</ActionButton>
{/if}
<style>
.inner {
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
padding-top: var(--spacing-xs);
padding-bottom: var(--spacing-xs);
}
.inner img {
width: 18px;
margin: 3px 10px 3px 3px;
}
.inner p {
margin: 0;
}
</style>

View File

@ -10,8 +10,9 @@
notifications,
} from "@budibase/bbui"
import { goto, params } from "@roxi/routify"
import { auth, organisation } from "stores/portal"
import { auth, organisation, oidc } from "stores/portal"
import GoogleButton from "./_components/GoogleButton.svelte"
import OIDCButton from "./_components/OIDCButton.svelte"
import Logo from "assets/bb-emblem.svg"
import { onMount } from "svelte"
@ -61,6 +62,7 @@
<Heading>Sign in to {company}</Heading>
</Layout>
<GoogleButton />
<OIDCButton oidcIcon={$oidc.logo} oidcName={$oidc.name} />
<Divider noGrid />
<Layout gap="XS" noPadding>
<Body size="S" textAlign="center">Sign in with email</Body>

View File

@ -0,0 +1,15 @@
<svg
width="25"
height="25 "
viewBox="0 0 100 100"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<g clip-path="url(#clip0)">
<path
d="M43,90c-88,-16,-21,-86,41,-51l9,-6v17h-26l8,-5c-55,-25,-86,29,-32,36z"
fill="#ccc"
/>
<path d="M43,90v-75l14,-9v75z" fill="#f60" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 319 B

View File

@ -1,5 +1,13 @@
<script>
import GoogleLogo from "./_logos/Google.svelte"
import OidcLogo from "./_logos/OIDC.svelte"
import MicrosoftLogo from "assets/microsoft-logo.png"
import Auth0Logo from "assets/auth0-logo.png"
import OktaLogo from "assets/okta-logo.png"
import OneLoginLogo from "assets/onelogin-logo.png"
import OidcLogoPng from "assets/oidc-logo.png"
import { isEqual, cloneDeep } from "lodash/fp"
import {
Button,
Heading,
@ -9,20 +17,25 @@
Layout,
Input,
Body,
Select,
Toggle,
} from "@budibase/bbui"
import { onMount } from "svelte"
import api from "builderStore/api"
import { organisation } from "stores/portal"
import { uuid } from "builderStore/uuid"
const ConfigTypes = {
Google: "google",
OIDC: "oidc",
// Github: "github",
// AzureAD: "ad",
}
const ConfigFields = {
const GoogleConfigFields = {
Google: ["clientID", "clientSecret", "callbackURL"],
}
const ConfigLabels = {
const GoogleConfigLabels = {
Google: {
clientID: "Client ID",
clientSecret: "Client secret",
@ -30,24 +43,167 @@
},
}
const OIDCConfigFields = {
Oidc: ["configUrl", "clientID", "clientSecret"],
}
const OIDCConfigLabels = {
Oidc: {
configUrl: "Config URL",
clientID: "Client ID",
clientSecret: "Client Secret",
},
}
let iconDropdownOptions = [
{
label: "Microsoft",
value: "Microsoft",
icon: MicrosoftLogo,
},
{
label: "Okta",
value: "Okta",
icon: OktaLogo,
},
{
label: "OneLogin",
value: "OneLogin",
icon: OneLoginLogo,
},
{
label: "Auth0",
value: "Auth0",
icon: Auth0Logo,
},
{
label: "OIDC",
value: "Oidc",
icon: OidcLogoPng,
},
{
label: "Upload your own",
value: "Upload",
},
]
let fileinput
let image
let google
let oidc
const providers = { google, oidc }
async function save(doc) {
try {
// Save an oauth config
const response = await api.post(`/api/admin/configs`, doc)
const json = await response.json()
if (response.status !== 200) throw new Error(json.message)
google._rev = json._rev
google._id = json._id
// control the state of the save button depending on whether form has changed
let originalGoogleDoc
let originalOidcDoc
let googleSaveButtonDisabled
let oidcSaveButtonDisabled
$: {
isEqual(providers.google?.config, originalGoogleDoc?.config)
? (googleSaveButtonDisabled = true)
: (googleSaveButtonDisabled = false)
isEqual(providers.oidc?.config, originalOidcDoc?.config)
? (oidcSaveButtonDisabled = true)
: (oidcSaveButtonDisabled = false)
}
notifications.success(`Settings saved.`)
} catch (err) {
notifications.error(`Failed to update OAuth settings. ${err}`)
}
// Create a flag so that it will only try to save completed forms
$: partialGoogle =
providers.google?.config?.clientID ||
providers.google?.config?.clientSecret ||
providers.google?.config?.callbackURL
$: partialOidc =
providers.oidc?.config?.configs[0].configUrl ||
providers.oidc?.config?.configs[0].clientID ||
providers.oidc?.config?.configs[0].clientSecret
$: googleComplete =
providers.google?.config?.clientID &&
providers.google?.config?.clientSecret &&
providers.google?.config?.callbackURL
$: oidcComplete =
providers.oidc?.config?.configs[0].configUrl &&
providers.oidc?.config?.configs[0].clientID &&
providers.oidc?.config?.configs[0].clientSecret
async function uploadLogo(file) {
let data = new FormData()
data.append("file", file)
const res = await api.post(
`/api/admin/configs/upload/logos_oidc/${file.name}`,
data,
{}
)
return await res.json()
}
const onFileSelected = e => {
let fileName = e.target.files[0].name
image = e.target.files[0]
providers.oidc.config.configs[0].logo = fileName
iconDropdownOptions.unshift({ label: fileName, value: fileName })
}
async function save(docs) {
// only if the user has provided an image, upload it.
image && uploadLogo(image)
let calls = []
docs.forEach(element => {
if (element.type === ConfigTypes.OIDC) {
//Add a UUID here so each config is distinguishable when it arrives at the login page.
element.config.configs.forEach(config => {
!config.uuid && (config.uuid = uuid())
})
if (partialOidc) {
if (!oidcComplete) {
notifications.error(
`Please fill in all required ${ConfigTypes.OIDC} fields`
)
} else {
calls.push(api.post(`/api/admin/configs`, element))
// turn the save button grey when clicked
oidcSaveButtonDisabled = true
originalOidcDoc = cloneDeep(providers.oidc)
}
}
}
if (element.type === ConfigTypes.Google) {
if (partialGoogle) {
if (!googleComplete) {
notifications.error(
`Please fill in all required ${ConfigTypes.Google} fields`
)
} else {
calls.push(api.post(`/api/admin/configs`, element))
googleSaveButtonDisabled = true
originalGoogleDoc = cloneDeep(providers.google)
}
}
}
})
calls.length &&
Promise.all(calls)
.then(responses => {
return Promise.all(
responses.map(response => {
return response.json()
})
)
})
.then(data => {
data.forEach(res => {
providers[res.type]._rev = res._rev
providers[res.type]._id = res._id
})
notifications.success(`Settings saved.`)
})
.catch(err => {
notifications.error(`Failed to update auth settings. ${err}`)
throw new Error(err.message)
})
}
onMount(async () => {
await organisation.init()
// fetch the configs for oauth
const googleResponse = await api.get(
`/api/admin/configs/${ConfigTypes.Google}`
@ -55,33 +211,77 @@
const googleDoc = await googleResponse.json()
if (!googleDoc._id) {
google = {
providers.google = {
type: ConfigTypes.Google,
config: {},
config: { activated: true },
}
originalGoogleDoc = cloneDeep(googleDoc)
} else {
originalGoogleDoc = cloneDeep(googleDoc)
providers.google = googleDoc
}
//Get the list of user uploaded logos and push it to the dropdown options.
//This needs to be done before the config call so they're available when the dropdown renders
const res = await api.get(`/api/admin/configs/logos_oidc`)
const configSettings = await res.json()
if (configSettings.config) {
const logoKeys = Object.keys(configSettings.config)
logoKeys.map(logoKey => {
const logoUrl = configSettings.config[logoKey]
iconDropdownOptions.unshift({
label: logoKey,
value: logoKey,
icon: logoUrl,
})
})
}
const oidcResponse = await api.get(`/api/admin/configs/${ConfigTypes.OIDC}`)
const oidcDoc = await oidcResponse.json()
if (!oidcDoc._id) {
console.log("hi")
providers.oidc = {
type: ConfigTypes.OIDC,
config: { configs: [{ activated: true }] },
}
} else {
google = googleDoc
console.log("hello")
originalOidcDoc = cloneDeep(oidcDoc)
providers.oidc = oidcDoc
}
})
</script>
<Layout>
<Layout gap="XS" noPadding>
<Heading size="M">OAuth</Heading>
<Heading size="M">Authentication</Heading>
<Body>
Every budibase app comes with basic authentication (email/password)
included. You can add additional authentication methods from the options
below.
</Body>
</Layout>
{#if google}
{#if providers.google}
<Divider />
<Layout gap="XS" noPadding>
<Heading size="S">
<span>
<div>
<GoogleLogo />
Google
</span>
<div class="google-save-button">
<div>
<Button
disabled={googleSaveButtonDisabled}
size="s"
cta
on:click={() => save([providers.google])}>Save</Button
>
</div>
</div>
</div>
</Heading>
<Body size="S">
To allow users to authenticate using their Google accounts, fill out the
@ -89,30 +289,127 @@
</Body>
</Layout>
<Layout gap="XS" noPadding>
{#each ConfigFields.Google as field}
{#each GoogleConfigFields.Google as field}
<div class="form-row">
<Label size="L">{ConfigLabels.Google[field]}</Label>
<Input bind:value={google.config[field]} />
<Label size="L">{GoogleConfigLabels.Google[field]}</Label>
<Input bind:value={providers.google.config[field]} />
</div>
{/each}
<div class="form-row">
<div class="field">
<Label size="L">Activated</Label>
<span class="alignedToggle">
<Toggle text="" bind:value={providers.google.config.activated} />
</span>
</div>
</div>
</Layout>
<div>
<Button cta on:click={() => save(google)}>Save</Button>
{/if}
{#if providers.oidc}
<Divider />
<Layout gap="XS" noPadding>
<Heading size="S">
<div>
<OidcLogo />
OpenID Connect
<div class="oidc-save-button">
<div>
<Button
disabled={oidcSaveButtonDisabled}
size="s"
cta
on:click={() => save([providers.oidc])}>Save</Button
>
</div>
</div>
</div></Heading
>
<Body size="S">
To allow users to authenticate using OIDC, fill out the fields below.
</Body>
</Layout>
<Layout gap="XS" noPadding>
{#each OIDCConfigFields.Oidc as field}
<div class="form-row">
<Label size="L">{OIDCConfigLabels.Oidc[field]}</Label>
<Input bind:value={providers.oidc.config.configs[0][field]} />
</div>
{/each}
<div class="form-row">
<Label size="L">Callback URL</Label>
<Input readonly placeholder="/api/admin/auth/oidc/callback" />
</div>
<br />
<Body size="S">
To customize your login button, fill out the fields below.
</Body>
<div class="form-row">
<Label size="L">Name</Label>
<Input bind:value={providers.oidc.config.configs[0].name} />
</div>
<div class="form-row">
<Label size="L">Icon</Label>
<Select
label=""
bind:value={providers.oidc.config.configs[0].logo}
options={iconDropdownOptions}
on:change={e => e.detail === "Upload" && fileinput.click()}
/>
</div>
<input
type="file"
accept=".jpg, .jpeg, .png"
on:change={e => onFileSelected(e)}
bind:this={fileinput}
/>
</Layout>
<div class="form-row">
<div class="field">
<Label size="L">Activated</Label>
<span class="alignedToggle">
<Toggle
text=""
bind:value={providers.oidc.config.configs[0].activated}
/>
</span>
</div>
</div>
{/if}
</Layout>
<style>
.field {
display: flex;
align-items: center;
}
.alignedToggle {
margin-left: 63%;
}
.form-row {
display: grid;
grid-template-columns: 20% 1fr;
grid-gap: var(--spacing-l);
align-items: center;
}
span {
display: flex;
align-items: center;
gap: var(--spacing-s);
}
input {
display: none;
}
.google-save-button {
display: inline-block;
margin-left: 400px;
}
.oidc-save-button {
display: inline-block;
margin-left: 320px;
}
</style>

View File

@ -4,3 +4,4 @@ export { admin } from "./admin"
export { apps } from "./apps"
export { email } from "./email"
export { auth } from "./auth"
export { oidc } from "./oidc"

View File

@ -0,0 +1,35 @@
import { writable, get } from "svelte/store"
import api from "builderStore/api"
import { auth } from "stores/portal"
const OIDC_CONFIG = {
logo: undefined,
name: undefined,
uuid: undefined,
}
export function createOidcStore() {
const store = writable(OIDC_CONFIG)
const { set, subscribe } = store
async function init() {
const tenantId = get(auth).tenantId
const res = await api.get(`/api/admin/configs/public/oidc?tenantId=${tenantId}`)
const json = await res.json()
if (json.status === 400) {
set(OIDC_CONFIG)
} else {
// Just use the first config for now. We will be support multiple logins buttons later on.
set(...json)
}
}
return {
subscribe,
set,
init,
}
}
export const oidc = createOidcStore()

View File

@ -1,11 +1,14 @@
import { writable, get } from "svelte/store"
import api from "builderStore/api"
import { auth } from "stores/portal"
const DEFAULT_CONFIG = {
platformUrl: "http://localhost:10000",
logoUrl: undefined,
docsUrl: undefined,
company: "Budibase",
oidc: undefined,
google: undefined,
}
export function createOrganisationStore() {
@ -13,7 +16,8 @@ export function createOrganisationStore() {
const { subscribe, set } = store
async function init() {
const res = await api.get(`/api/admin/configs/public`)
const tenantId = get(auth).tenantId
const res = await api.get(`/api/admin/configs/public?tenantId=${tenantId}`)
const json = await res.json()
if (json.status === 400) {

View File

@ -39,6 +39,7 @@
"koa-static": "^5.0.0",
"node-fetch": "^2.6.1",
"nodemailer": "^6.5.0",
"@techpass/passport-openidconnect": "^0.3.0",
"passport-google-oauth": "^2.0.0",
"passport-jwt": "^4.0.0",
"passport-local": "^1.0.0",

View File

@ -1,23 +1,26 @@
const authPkg = require("@budibase/auth")
const { google } = require("@budibase/auth/src/middleware")
const { oidc } = require("@budibase/auth/src/middleware")
const { Configs, EmailTemplatePurpose } = require("../../../constants")
const { sendEmail, isEmailConfigured } = require("../../../utilities/email")
const { clearCookie, getGlobalUserByEmail, hash } = authPkg.utils
const { setCookie, getCookie, clearCookie, getGlobalUserByEmail, hash } =
authPkg.utils
const { Cookies } = authPkg.constants
const { passport } = authPkg.auth
const { checkResetPasswordCode } = require("../../../utilities/redis")
const { getGlobalDB } = authPkg.db
async function authInternal(ctx, user, err = null) {
async function authInternal(ctx, user, err = null, info = null) {
if (err) {
return ctx.throw(403, "Unauthorized")
console.error("Authentication error", err)
return ctx.throw(403, info ? info : "Unauthorized")
}
const expires = new Date()
expires.setDate(expires.getDate() + 1)
if (!user) {
return ctx.throw(403, "Unauthorized")
return ctx.throw(403, info ? info : "Unauthorized")
}
// just store the user ID
@ -30,8 +33,8 @@ async function authInternal(ctx, user, err = null) {
}
exports.authenticate = async (ctx, next) => {
return passport.authenticate("local", async (err, user) => {
await authInternal(ctx, user, err)
return passport.authenticate("local", async (err, user, info) => {
await authInternal(ctx, user, err, info)
delete user.token
@ -122,8 +125,53 @@ exports.googleAuth = async (ctx, next) => {
return passport.authenticate(
strategy,
{ successRedirect: "/", failureRedirect: "/error" },
async (err, user) => {
await authInternal(ctx, user, err)
async (err, user, info) => {
await authInternal(ctx, user, err, info)
ctx.redirect("/")
}
)(ctx, next)
}
async function oidcStrategyFactory(ctx, configId) {
const db = getGlobalDB(ctx.params.tenantId)
const config = await authPkg.db.getScopedConfig(db, {
type: Configs.OIDC,
group: ctx.query.group,
})
const chosenConfig = config.configs.filter(c => c.uuid === configId)[0]
const callbackUrl = `${ctx.protocol}://${ctx.host}/api/admin/auth/oidc/callback`
return oidc.strategyFactory(chosenConfig, callbackUrl)
}
/**
* The initial call that OIDC authentication makes to take you to the configured OIDC login screen.
* On a successful login, you will be redirected to the oidcAuth callback route.
*/
exports.oidcPreAuth = async (ctx, next) => {
const { configId } = ctx.params
const strategy = await oidcStrategyFactory(ctx, configId)
setCookie(ctx, configId, Cookies.OIDC_CONFIG)
return passport.authenticate(strategy, {
// required 'openid' scope is added by oidc strategy factory
scope: ["profile", "email"],
})(ctx, next)
}
exports.oidcAuth = async (ctx, next) => {
const configId = getCookie(ctx, Cookies.OIDC_CONFIG)
const strategy = await oidcStrategyFactory(ctx, configId)
return passport.authenticate(
strategy,
{ successRedirect: "/", failureRedirect: "/error" },
async (err, user, info) => {
await authInternal(ctx, user, err, info)
ctx.redirect("/")
}

View File

@ -97,23 +97,66 @@ exports.find = async function (ctx) {
}
}
exports.publicSettings = async function (ctx) {
exports.publicOidc = async function (ctx) {
const db = getGlobalDBFromCtx(ctx)
try {
// Find the config with the most granular scope based on context
const config = await getScopedFullConfig(db, {
type: Configs.SETTINGS,
const oidcConfig = await getScopedFullConfig(db, {
type: Configs.OIDC,
})
if (!config) {
if (!oidcConfig) {
ctx.body = {}
} else {
ctx.body = config
ctx.body = oidcConfig.config.configs.map(config => ({
logo: config.logo,
name: config.name,
uuid: config.uuid,
}))
}
} catch (err) {
ctx.throw(err.status, err)
}
}
exports.publicSettings = async function (ctx) {
const db = getGlobalDBFromCtx(ctx)
try {
// Find the config with the most granular scope based on context
const publicConfig = await getScopedFullConfig(db, {
type: Configs.SETTINGS,
})
const googleConfig = await getScopedFullConfig(db, {
type: Configs.GOOGLE,
})
const oidcConfig = await getScopedFullConfig(db, {
type: Configs.OIDC,
})
let config
if (!publicConfig) {
config = {
config: {},
}
} else {
config = publicConfig
}
config.config.google = !googleConfig
? !!googleConfig
: googleConfig.config.activated
config.config.oidc = !oidcConfig
? !!oidcConfig
: oidcConfig.config.configs[0].activated
ctx.body = config
} catch (err) {
ctx.throw(err.status, err)
}
}
exports.upload = async function (ctx) {
if (ctx.request.files == null || ctx.request.files.file.length > 1) {
ctx.throw(400, "One file must be uploaded.")
@ -121,12 +164,8 @@ exports.upload = async function (ctx) {
const file = ctx.request.files.file
const { type, name } = ctx.params
const fileExtension = [...file.name.split(".")].pop()
// filenames converted to UUIDs so they are unique
const processedFileName = `${name}.${fileExtension}`
const bucket = ObjectStoreBuckets.GLOBAL
const key = `${type}/${processedFileName}`
const key = `${type}/${name}`
await upload({
bucket,
filename: key,
@ -145,7 +184,7 @@ exports.upload = async function (ctx) {
}
}
const url = `/${bucket}/${key}`
cfgStructure.config[`${name}Url`] = url
cfgStructure.config[`${name}`] = url
// write back to db with url updated
await db.put(cfgStructure)
@ -183,10 +222,14 @@ exports.configChecklist = async function (ctx) {
})
// They have set up Google Auth
const oauthConfig = await getScopedFullConfig(db, {
const googleConfig = await getScopedFullConfig(db, {
type: Configs.GOOGLE,
})
// They have set up OIDC
const oidcConfig = await getScopedFullConfig(db, {
type: Configs.OIDC,
})
// They have set up an admin user
const users = await db.allDocs(
getGlobalUserParams(null, {
@ -199,7 +242,7 @@ exports.configChecklist = async function (ctx) {
apps: apps.length,
smtp: !!smtpConfig,
adminUser,
oauth: !!oauthConfig,
sso: !!googleConfig || !!oidcConfig,
}
} catch (err) {
ctx.throw(err.status, err)

View File

@ -5,6 +5,29 @@ const { routes } = require("./routes")
const { buildAuthMiddleware, auditLog } = require("@budibase/auth").auth
const PUBLIC_ENDPOINTS = [
{
// this covers all of the POST auth routes
route: "/api/admin/auth/:tenantId",
method: "POST",
},
{
// this covers all of the GET auth routes
route: "/api/admin/auth/:tenantId",
method: "GET",
},
{
// this covers all of the public config routes
route: "/api/admin/configs/public",
method: "GET",
},
{
route: "api/admin/tenants/enabled",
method: "GET",
},
{
route: "/api/admin/configs/checklist",
method: "GET",
},
{
route: "/api/admin/users/init",
method: "POST",
@ -13,38 +36,6 @@ const PUBLIC_ENDPOINTS = [
route: "/api/admin/users/invite/accept",
method: "POST",
},
{
route: "/api/admin/auth/:tenantId/login",
method: "POST",
},
{
route: "/api/admin/auth/:tenantId/google",
method: "GET",
},
{
route: "/api/admin/auth/:tenantId/google/callback",
method: "GET",
},
{
route: "/api/admin/auth/:tenantId/reset",
method: "POST",
},
{
route: "/api/admin/auth/:tenantId/reset/update",
method: "POST",
},
{
route: "/api/admin/configs/checklist",
method: "GET",
},
{
route: "/api/admin/configs/public",
method: "GET",
},
{
route: "api/admin/tenants/enabled",
method: "GET",
}
]
const router = new Router()

View File

@ -47,5 +47,7 @@ router
.post("/api/admin/auth/logout", authController.logout)
.get("/api/admin/auth/:tenantId/google", authController.googlePreAuth)
.get("/api/admin/auth/:tenantId/google/callback", authController.googleAuth)
.get("/api/admin/auth/:tenantId/oidc/configs/:configId", authController.oidcPreAuth)
.get("/api/admin/auth/:tenantId/oidc/callback", authController.oidcAuth)
module.exports = router

View File

@ -3,7 +3,7 @@ const controller = require("../../controllers/admin/configs")
const joiValidator = require("../../../middleware/joi-validator")
const adminOnly = require("../../../middleware/adminOnly")
const Joi = require("joi")
const { Configs, ConfigUploads } = require("../../../constants")
const { Configs } = require("../../../constants")
const router = Router()
@ -38,6 +38,24 @@ function googleValidation() {
clientID: Joi.string().required(),
clientSecret: Joi.string().required(),
callbackURL: Joi.string().required(),
activated: Joi.boolean().required(),
}).unknown(true)
}
function oidcValidation() {
// prettier-ignore
return Joi.object({
configs: Joi.array().items(
Joi.object({
clientID: Joi.string().required(),
clientSecret: Joi.string().required(),
configUrl: Joi.string().required(),
logo: Joi.string().allow("", null),
name: Joi.string().allow("", null),
uuid: Joi.string().required(),
activated: Joi.boolean().required(),
})
).required(true)
}).unknown(true)
}
@ -54,7 +72,8 @@ function buildConfigSaveValidation() {
{ is: Configs.SMTP, then: smtpValidation() },
{ is: Configs.SETTINGS, then: settingValidation() },
{ is: Configs.ACCOUNT, then: Joi.object().unknown(true) },
{ is: Configs.GOOGLE, then: googleValidation() }
{ is: Configs.GOOGLE, then: googleValidation() },
{ is: Configs.OIDC, then: oidcValidation() }
],
}),
}).required(),
@ -65,7 +84,7 @@ function buildUploadValidation() {
// prettier-ignore
return joiValidator.params(Joi.object({
type: Joi.string().valid(...Object.values(Configs)).required(),
name: Joi.string().valid(...Object.values(ConfigUploads)).required(),
name: Joi.string().required(),
}).required())
}
@ -83,7 +102,7 @@ router
buildConfigSaveValidation(),
controller.save
)
.delete("/api/admin/configs/:id", adminOnly, controller.destroy)
.delete("/api/admin/configs/:id/:rev", adminOnly, controller.destroy)
.get("/api/admin/configs", controller.fetch)
.get("/api/admin/configs/checklist", controller.configChecklist)
.get(
@ -92,6 +111,7 @@ router
controller.fetch
)
.get("/api/admin/configs/public", controller.publicSettings)
.get("/api/admin/configs/public/oidc", controller.publicOidc)
.get("/api/admin/configs/:type", buildConfigGetValidation(), controller.find)
.post(
"/api/admin/configs/upload/:type/:name",

View File

@ -1,5 +1,7 @@
const setup = require("./utilities")
const TENANT_ID = "default"
jest.mock("nodemailer")
const sendMailMock = setup.emailMock()
@ -14,13 +16,17 @@ describe("/api/admin/auth", () => {
afterAll(setup.afterAll)
afterEach(() => {
jest.clearAllMocks()
})
it("should be able to generate password reset email", async () => {
// initially configure settings
await config.saveSmtpConfig()
await config.saveSettingsConfig()
await config.createUser("test@test.com")
const res = await request
.post(`/api/admin/auth/reset`)
.post(`/api/admin/auth/${TENANT_ID}/reset`)
.send({
email: "test@test.com",
})
@ -30,14 +36,14 @@ describe("/api/admin/auth", () => {
expect(sendMailMock).toHaveBeenCalled()
const emailCall = sendMailMock.mock.calls[0][0]
// after this URL there should be a code
const parts = emailCall.html.split("http://localhost:10000/builder/auth/reset?code=")
const parts = emailCall.html.split(`http://localhost:10000/builder/auth/${TENANT_ID}/reset?code=`)
code = parts[1].split("\"")[0]
expect(code).toBeDefined()
})
it("should allow resetting user password with code", async () => {
const res = await request
.post(`/api/admin/auth/reset/update`)
.post(`/api/admin/auth/${TENANT_ID}/reset/update`)
.send({
password: "newpassword",
resetCode: code,
@ -46,4 +52,56 @@ describe("/api/admin/auth", () => {
.expect(200)
expect(res.body).toEqual({ message: "password reset successfully." })
})
describe("oidc", () => {
const auth = require("@budibase/auth").auth
// mock the oidc strategy implementation and return value
strategyFactory = jest.fn()
mockStrategyReturn = jest.fn()
strategyFactory.mockReturnValue(mockStrategyReturn)
auth.oidc.strategyFactory = strategyFactory
const passportSpy = jest.spyOn(auth.passport, "authenticate")
let oidcConf
let chosenConfig
let configId
beforeEach(async () => {
oidcConf = await config.saveOIDCConfig()
chosenConfig = oidcConf.config.configs[0]
configId = chosenConfig.uuid
})
afterEach(() => {
expect(strategyFactory).toBeCalledWith(
chosenConfig,
`http://127.0.0.1:4003/api/admin/auth/${TENANT_ID}/oidc/callback` // calculated url
)
})
describe("oidc configs", () => {
it("should load strategy and delegate to passport", async () => {
await request.get(`/api/admin/auth/${TENANT_ID}/oidc/configs/${configId}`)
expect(passportSpy).toBeCalledWith(mockStrategyReturn, {
scope: ["profile", "email"],
})
expect(passportSpy.mock.calls.length).toBe(1);
})
})
describe("oidc callback", () => {
it("should load strategy and delegate to passport", async () => {
await request.get(`/api/admin/auth/${TENANT_ID}/oidc/callback`)
.set(config.getOIDConfigCookie(configId))
expect(passportSpy).toBeCalledWith(mockStrategyReturn, {
successRedirect: "/", failureRedirect: "/error"
}, expect.anything())
expect(passportSpy.mock.calls.length).toBe(1);
})
})
})
})

View File

@ -6,6 +6,7 @@ const { Cookies } = require("@budibase/auth").constants
const { Configs, LOGO_URL } = require("../../../../constants")
const { getGlobalUserByEmail } = require("@budibase/auth").utils
const { createASession } = require("@budibase/auth/sessions")
const { newid } = require("../../../../../../auth/src/hashing")
const TENANT_ID = "default"
@ -69,6 +70,12 @@ class TestConfiguration {
}
}
cookieHeader(cookies) {
return {
Cookie: [cookies],
}
}
defaultHeaders() {
const user = {
_id: "us_uuid1",
@ -79,7 +86,7 @@ class TestConfiguration {
const authToken = jwt.sign(user, env.JWT_SECRET)
return {
Accept: "application/json",
Cookie: [`${Cookies.Auth}=${authToken}`],
...this.cookieHeader([`${Cookies.Auth}=${authToken}`]),
}
}
@ -158,6 +165,33 @@ class TestConfiguration {
)
}
getOIDConfigCookie(configId) {
const token = jwt.sign(configId, env.JWT_SECRET)
return this.cookieHeader([[`${Cookies.OIDC_CONFIG}=${token}`]])
}
async saveOIDCConfig() {
await this.deleteConfig(Configs.OIDC)
const config = {
type: Configs.OIDC,
config: {
configs: [
{
configUrl: "http://someconfigurl",
clientID: "clientId",
clientSecret: "clientSecret",
logo: "Microsoft",
name: "Active Directory",
uuid: newid(),
},
],
},
}
await this._req(config, null, controllers.config.save)
return config
}
async saveSmtpConfig() {
await this.deleteConfig(Configs.SMTP)
await this._req(

View File

@ -12,6 +12,7 @@ exports.Configs = Configs
exports.ConfigUploads = {
LOGO: "logo",
OIDC_LOGO: "oidc_logo",
}
const TemplateTypes = {

View File

@ -5,6 +5,7 @@ require("@budibase/auth").init(CouchDB)
const Koa = require("koa")
const destroyable = require("server-destroy")
const koaBody = require("koa-body")
const koaSession = require("koa-session")
const { passport } = require("@budibase/auth").auth
const logger = require("koa-pino-logger")
const http = require("http")
@ -13,8 +14,11 @@ const redis = require("./utilities/redis")
const app = new Koa()
app.keys = ["secret", "key"]
// set up top level koa middleware
app.use(koaBody({ multipart: true }))
app.use(koaSession(app))
app.use(
logger({

View File

@ -566,6 +566,17 @@
dependencies:
defer-to-connect "^2.0.0"
"@techpass/passport-openidconnect@^0.3.0":
version "0.3.0"
resolved "https://registry.yarnpkg.com/@techpass/passport-openidconnect/-/passport-openidconnect-0.3.0.tgz#a60b2bbf3f262649a5a02d5d186219944acc3010"
integrity sha512-bVsPwl66s7J7GHxTPlW/RJYhZol9SshNznQsx83OOh9G+JWFGoeWxh+xbX+FTdJNoUvGIGbJnpWPY2wC6NOHPw==
dependencies:
base64url "^3.0.1"
oauth "^0.9.15"
passport-strategy "^1.0.0"
request "^2.88.0"
webfinger "^0.4.2"
"@types/babel__core@^7.0.0", "@types/babel__core@^7.1.7":
version "7.1.14"
resolved "https://registry.yarnpkg.com/@types/babel__core/-/babel__core-7.1.14.tgz#faaeefc4185ec71c389f4501ee5ec84b170cc402"
@ -1058,7 +1069,7 @@ base64-js@^1.0.2, base64-js@^1.3.1:
resolved "https://registry.yarnpkg.com/base64-js/-/base64-js-1.5.1.tgz#1b1b440160a5bf7ad40b650f095963481903930a"
integrity sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==
base64url@3.x.x:
base64url@3.x.x, base64url@^3.0.1:
version "3.0.1"
resolved "https://registry.yarnpkg.com/base64url/-/base64url-3.0.1.tgz#6399d572e2bc3f90a9a8b22d5dbb0a32d33f788d"
integrity sha512-ir1UPr3dkwexU7FdV8qBBbNDRUhMmIekYMFZfi+C/sLNnRESKPl23nB9b2pltqfOQNnGzsDdId90AEtG5tCx4A==
@ -4183,7 +4194,7 @@ oauth-sign@~0.9.0:
resolved "https://registry.yarnpkg.com/oauth-sign/-/oauth-sign-0.9.0.tgz#47a7b016baa68b5fa0ecf3dee08a85c679ac6455"
integrity sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ==
oauth@0.9.x:
oauth@0.9.x, oauth@^0.9.15:
version "0.9.15"
resolved "https://registry.yarnpkg.com/oauth/-/oauth-0.9.15.tgz#bd1fefaf686c96b75475aed5196412ff60cfb9c1"
integrity sha1-vR/vr2hslrdUda7VGWQS/2DPucE=
@ -4933,7 +4944,7 @@ request-promise-native@^1.0.9:
stealthy-require "^1.1.1"
tough-cookie "^2.3.3"
request@^2.88.2:
request@^2.88.0, request@^2.88.2:
version "2.88.2"
resolved "https://registry.yarnpkg.com/request/-/request-2.88.2.tgz#d73c918731cb5a87da047e207234146f664d12b3"
integrity sha512-MsvtOrfG9ZcrOwAW+Qi+F6HbD0CWXEh9ou77uOb7FM2WPhwT7smM833PzanhJLsgXjN89Ir6V2PczXNnMpwKhw==
@ -5080,7 +5091,7 @@ sax@1.2.1:
resolved "https://registry.yarnpkg.com/sax/-/sax-1.2.1.tgz#7b8e656190b228e81a66aea748480d828cd2d37a"
integrity sha1-e45lYZCyKOgaZq6nSEgNgozS03o=
sax@>=0.6.0:
sax@>=0.1.1, sax@>=0.6.0:
version "1.2.4"
resolved "https://registry.yarnpkg.com/sax/-/sax-1.2.4.tgz#2816234e2378bddc4e5354fab5caa895df7100d9"
integrity sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==
@ -5390,6 +5401,11 @@ stealthy-require@^1.1.1:
resolved "https://registry.yarnpkg.com/stealthy-require/-/stealthy-require-1.1.1.tgz#35b09875b4ff49f26a777e509b3090a3226bf24b"
integrity sha1-NbCYdbT/SfJqd35QmzCQoyJr8ks=
step@0.0.x:
version "0.0.6"
resolved "https://registry.yarnpkg.com/step/-/step-0.0.6.tgz#143e7849a5d7d3f4a088fe29af94915216eeede2"
integrity sha1-FD54SaXX0/SgiP4pr5SRUhbu7eI=
string-length@^4.0.1:
version "4.0.2"
resolved "https://registry.yarnpkg.com/string-length/-/string-length-4.0.2.tgz#a8a8dc7bd5c1a82b9b3c8b87e125f66871b6e57a"
@ -5923,6 +5939,14 @@ walker@^1.0.7, walker@~1.0.5:
dependencies:
makeerror "1.0.x"
webfinger@^0.4.2:
version "0.4.2"
resolved "https://registry.yarnpkg.com/webfinger/-/webfinger-0.4.2.tgz#3477a6d97799461896039fcffc650b73468ee76d"
integrity sha1-NHem2XeZRhiWA5/P/GULc0aO520=
dependencies:
step "0.0.x"
xml2js "0.1.x"
webidl-conversions@^5.0.0:
version "5.0.0"
resolved "https://registry.yarnpkg.com/webidl-conversions/-/webidl-conversions-5.0.0.tgz#ae59c8a00b121543a2acc65c0434f57b0fc11aff"
@ -6031,6 +6055,13 @@ xml-name-validator@^3.0.0:
resolved "https://registry.yarnpkg.com/xml-name-validator/-/xml-name-validator-3.0.0.tgz#6ae73e06de4d8c6e47f9fb181f78d648ad457c6a"
integrity sha512-A5CUptxDsvxKJEU3yO6DuWBSJz/qizqzJKOMIfUJHETbBw/sFaDxgd6fxm1ewUaM0jZ444Fc5vC5ROYurg/4Pw==
xml2js@0.1.x:
version "0.1.14"
resolved "https://registry.yarnpkg.com/xml2js/-/xml2js-0.1.14.tgz#5274e67f5a64c5f92974cd85139e0332adc6b90c"
integrity sha1-UnTmf1pkxfkpdM2FE54DMq3GuQw=
dependencies:
sax ">=0.1.1"
xml2js@0.4.19:
version "0.4.19"
resolved "https://registry.yarnpkg.com/xml2js/-/xml2js-0.4.19.tgz#686c20f213209e94abf0d1bcf1efaa291c7827a7"