Compare commits

..

198 Commits

Author SHA1 Message Date
Johannes Zellner 8b295fbfdb total stats are reported directly as single value 2022-10-14 12:00:24 +02:00
Johannes Zellner 4e47a1ad3b Clean stats api response to have specific response types 2022-10-14 11:25:43 +02:00
Johannes Zellner 8f91991e1e Also collect total I/O stats for the containers 2022-10-14 11:15:52 +02:00
Girish Ramakrishnan ae66692eda Ensure collectd directory 2022-10-14 10:43:30 +02:00
Girish Ramakrishnan 7cb326cfff no camel case in filenames 2022-10-14 08:22:04 +02:00
Girish Ramakrishnan eb5c90a2e7 du: do not crash when app dir is missing
this can happen when the app is installing/uninstalling
2022-10-13 23:35:01 +02:00
Girish Ramakrishnan 91d1d0b74b add to changes 2022-10-13 23:12:20 +02:00
Girish Ramakrishnan 351292ce1a graph: return sum cpu value 2022-10-13 23:03:31 +02:00
Girish Ramakrishnan ca4e1e207c return cpuCount from app/service graphs as well 2022-10-13 22:38:44 +02:00
Girish Ramakrishnan 1872cea763 graphs: do not average cpu use
Show like htop/top: cpu core count * 100
2022-10-13 22:36:20 +02:00
Girish Ramakrishnan 4015afc69c graphs: send service graphs 2022-10-13 20:52:22 +02:00
Johannes Zellner 6d8c3febac Also add rootDSE to the directory server 2022-10-12 22:13:54 +02:00
Girish Ramakrishnan b5da4143c9 graphs: add app response in system graphs 2022-10-12 22:08:10 +02:00
Girish Ramakrishnan 4fe0402735 box data is separate from mail data already 2022-10-12 11:59:28 +02:00
Girish Ramakrishnan 4a3d85a269 add docker disk usage tests 2022-10-12 10:57:22 +02:00
Girish Ramakrishnan fa7c0a6e1b add disks tests 2022-10-12 10:45:29 +02:00
Girish Ramakrishnan 62d68e2733 graphs: remove the disk info 2022-10-12 10:30:02 +02:00
Girish Ramakrishnan edb6ed91fe add disk usage task 2022-10-12 10:26:21 +02:00
Girish Ramakrishnan a3f7ce15ab system: rework disks api to return by filesystem 2022-10-12 09:42:14 +02:00
Girish Ramakrishnan 4348556dc7 Fix applinks test 2022-10-12 09:37:25 +02:00
Girish Ramakrishnan deb6d78e4d bump addon timeouts 2022-10-11 23:33:35 +02:00
Girish Ramakrishnan 3c963329e9 du: exclude option 2022-10-11 23:14:50 +02:00
Girish Ramakrishnan 656f3fcc13 add system.du 2022-10-11 23:06:54 +02:00
Girish Ramakrishnan 760301ce02 Add docker.df 2022-10-11 23:06:51 +02:00
Girish Ramakrishnan 6f61145b01 configurecollectd.sh is no more 2022-10-11 21:04:25 +02:00
Johannes Zellner cbaf86b8c7 Use counter values for docker stats in collectd and grafana queries 2022-10-11 19:06:40 +02:00
Girish Ramakrishnan 9d35756db5 graphs: just query graphite IP instead of localhost mapping 2022-10-11 12:44:37 +02:00
Girish Ramakrishnan 22790fd9b7 system: include only ram info for graphs
app graphs only contain ram info since that is what docker stats provides
2022-10-11 11:54:06 +02:00
Johannes Zellner ad29f51833 Fixup typo guage -> gauge in docker-stats.py 2022-10-11 10:54:53 +02:00
Girish Ramakrishnan 3caffdb4e1 Rework app stats
Previously, the du plugin was collecting data every 20 seconds but
carbon was configured to only keep data every 12 hours causing much
confusion.

In the process of reworking this, it was determined:

* No need to collect disk usage info over time. Not sure how that is useful
* Instead, collect CPU/Network/Block info over time. We get this now from docker stats
* We also collect info about the services (addon containers)
* No need to reconfigure collectd for each app change anymore since there is no per
app collectd configuration anymore.
2022-10-10 21:13:26 +02:00
Girish Ramakrishnan 2133eab341 postgresql: fix issue when restoring large dumps 2022-10-10 12:30:26 +02:00
Johannes Zellner 25379f1d21 Prevent code from crashing when DO access token contains non-ascii characters 2022-10-07 11:25:17 +02:00
Johannes Zellner cb8d90699b Better feedback if no applink schema is provided 2022-10-06 19:49:33 +02:00
Johannes Zellner 6e4e8bf74d Add applink upstreamUri validation 2022-10-06 19:35:07 +02:00
Johannes Zellner 87a00b9209 Fixup app link icon fetching and do not overwrite upstreamUri with redirect 2022-10-06 19:23:15 +02:00
Girish Ramakrishnan d51b022721 applinks: make get return null
this style matches rest of the code base
2022-10-06 11:32:42 +02:00
Girish Ramakrishnan cb9b9272cd lint 2022-10-06 11:27:12 +02:00
Girish Ramakrishnan 7dbb677af4 postgresql: move config to runtime for debuggability 2022-10-06 10:13:49 +02:00
Girish Ramakrishnan 071202fb00 mail: log error 2022-10-04 10:57:42 +02:00
Girish Ramakrishnan fc7414cce6 support: require superadmin 2022-10-04 10:25:11 +02:00
Girish Ramakrishnan acb92c8865 mail queue: fix search + pagination 2022-10-03 10:51:35 +02:00
Girish Ramakrishnan c3793da5bb split checkPrecondition so it can be used in cleaner as well 2022-10-02 17:41:21 +02:00
Girish Ramakrishnan 4f4a0ec289 use mount code to check mount status 2022-10-02 16:51:03 +02:00
Girish Ramakrishnan a4a9b52966 Clarify error message 2022-10-02 16:38:12 +02:00
Girish Ramakrishnan 56b981a52b backups: when checking mount status, ignore the prefix 2022-10-02 16:33:04 +02:00
Girish Ramakrishnan 074e9cfd93 rename getRootPath to getBackupRootPath 2022-10-02 16:26:27 +02:00
Girish Ramakrishnan 9d17c6606b rename to checkBackupPreconditions
since this is called only by the backup logic
2022-10-02 16:20:14 +02:00
Girish Ramakrishnan b32288050e backups: check mount status before checking available size 2022-10-02 16:16:30 +02:00
Girish Ramakrishnan 4aab03bb07 import: cleanup app import logic 2022-10-02 10:08:50 +02:00
Girish Ramakrishnan 9f788c2c57 backup: reduce memory logs 2022-10-01 20:16:08 +02:00
Girish Ramakrishnan 84ba333aa1 app proxy: disable TLS check in app health monitor 2022-10-01 11:47:52 +02:00
Girish Ramakrishnan c07fe4195f eventlog: preserve last 2 months 2022-10-01 11:01:41 +02:00
Girish Ramakrishnan 92112986a7 7.3.1 changes 2022-10-01 08:46:13 +02:00
Girish Ramakrishnan 54af286fcd app proxy: workaround for nginx not starting if upstream is down
https://sandro-keil.de/blog/let-nginx-start-if-upstream-host-is-unavailable-or-down/

without a resolver, dns names do not resolve
2022-09-30 10:36:44 +02:00
Girish Ramakrishnan 7b5df02a0e app proxy: validate uri 2022-09-29 18:56:10 +02:00
Girish Ramakrishnan 4f0e0706b2 backups: fix id
avoid box_box_ and mail_mail_ in backup ids
2022-09-29 18:01:19 +02:00
Girish Ramakrishnan 1f74febdb0 mail: do not clear eventlog on restart 2022-09-28 22:16:32 +02:00
Girish Ramakrishnan 49bf333355 merge these changelog entries 2022-09-28 18:22:00 +02:00
Girish Ramakrishnan c4af06dd66 remove duplicate changelog entry 2022-09-28 18:21:12 +02:00
Johannes Zellner f5f9a8e520 Send 404 if applink icon does not exist 2022-09-28 15:18:05 +02:00
Johannes Zellner ae376774e4 Ensure we don't put empty applink icon buffers in db 2022-09-28 15:10:17 +02:00
Johannes Zellner ff8c2184f6 Convert applink ts to timestamp 2022-09-28 14:59:30 +02:00
Johannes Zellner a7b056a84c Some tweaks for better app link detection logic 2022-09-28 14:23:45 +02:00
Girish Ramakrishnan 131d456329 Add cloudflare R2 2022-09-27 19:44:20 +02:00
Girish Ramakrishnan d4bba93dbf cloudron-setup: Fix display on newline 2022-09-27 11:25:11 +02:00
Johannes Zellner e332ad96e4 Remove duplicate changes for 7.3.0 2022-09-26 17:42:39 +02:00
Girish Ramakrishnan c455325875 More changes 2022-09-26 09:37:49 +02:00
Girish Ramakrishnan 88e9f751ea mail: update for logging changes 2022-09-26 09:37:36 +02:00
Johannes Zellner 8677e86ace Add authorization to all routes 2022-09-24 21:27:43 +02:00
Johannes Zellner cde22cd0a3 Add token scope tests in routes 2022-09-24 20:56:43 +02:00
Johannes Zellner 6d7f7fbc9a Add some more token scope tests 2022-09-24 18:52:41 +02:00
Johannes Zellner 858c85ee85 Fixup more tests 2022-09-24 18:26:31 +02:00
Johannes Zellner 15d473d506 Fixup some token tests and error handling 2022-09-24 17:29:42 +02:00
Johannes Zellner 70d3040135 Validate token scopes 2022-09-23 13:09:07 +02:00
Johannes Zellner 56c567ac86 Add token scopes 2022-09-22 22:28:59 +02:00
Girish Ramakrishnan 1f5831b79e rename queue route 2022-09-22 19:48:20 +02:00
Girish Ramakrishnan 6382216dc5 mail: proxy queue routes correctly 2022-09-20 20:02:54 +02:00
Johannes Zellner 81b59eae36 improve applink businesslogic tests and fixup api 2022-09-19 21:00:44 +02:00
Girish Ramakrishnan bc3cb6acb5 more changes 2022-09-19 20:56:28 +02:00
Johannes Zellner fa768ad305 Support secureserver.net nameservers from GoDaddy 2022-09-19 19:58:52 +02:00
Johannes Zellner 5184e017c9 Error the task waited for fails in tests 2022-09-19 18:20:27 +02:00
Johannes Zellner d2ea6b2002 Fixup appstore tests 2022-09-19 17:21:55 +02:00
Johannes Zellner 3fcc3ea1aa Fixup reverseproxy tests 2022-09-19 17:04:44 +02:00
Girish Ramakrishnan 15877f45b8 more changes 2022-09-19 10:42:19 +02:00
Girish Ramakrishnan 0a514323a9 Update 7.3 changes 2022-09-19 10:41:48 +02:00
Johannes Zellner 1c07ec219c Do not query disk usage for apps without localstorage 2022-09-16 17:10:07 +02:00
Girish Ramakrishnan 82142f3f31 mail: fix issue where signature was appended to text attachments 2022-09-16 12:40:33 +02:00
Johannes Zellner 554dec640a Rework system graphs api 2022-09-15 16:07:08 +02:00
Girish Ramakrishnan d176ff2582 graphs: move system graph queries to the backend 2022-09-15 12:40:52 +02:00
Girish Ramakrishnan bd7ee437a8 collectd: fix memory stat collection configuration
https://www.kernel.org/doc/html/latest/admin-guide/cgroup-v1/memory.html#usage-in-bytes says
this is the most efficient approach for v1. It says RSS+CACHE(+SWAP) is the more accurate value.
Elsewhere in the note in https://www.kernel.org/doc/html/latest/admin-guide/cgroup-v1/memory.html#stat-file,
it says "‘rss + mapped_file” will give you resident set size of cgroup." Overall, it's not clear how
to compute the values so we just use the file.

https://www.kernel.org/doc/html/latest/admin-guide/cgroup-v2.html is better. https://www.kernel.org/doc/html/latest/admin-guide/cgroup-v2.html#memory
says the values are separated out.
2022-09-14 18:15:26 +02:00
Girish Ramakrishnan 0250661402 Revert spurious change 2022-09-14 17:59:44 +02:00
Girish Ramakrishnan 9cef08aa6a mail relay: do not accept TLS servers
haraka can only relay via STARTTLS
2022-09-14 17:42:21 +02:00
Johannes Zellner bead9589a1 Move app graphs graphite query to backend 2022-09-14 14:39:28 +02:00
Girish Ramakrishnan c5b631c0e5 mail: catch all is already fully qualified 2022-09-11 13:49:20 +02:00
Girish Ramakrishnan 4e75694ac6 mail: require catch all to be absolute 2022-09-11 12:56:58 +02:00
Girish Ramakrishnan 2a93c703ef mailserver: add queue routes 2022-08-31 08:45:18 +02:00
Johannes Zellner 3c92971665 If backup storage precondition is not met we want to throw 2022-08-29 22:54:23 +02:00
Johannes Zellner 563391c2f1 remove PermitRootLogin check as we now use cloudron-support user 2022-08-25 18:53:09 +02:00
Girish Ramakrishnan d4555886f4 add note on the reason for the flag 2022-08-25 16:36:57 +02:00
Girish Ramakrishnan a584fad278 proxyAuth: add supportsBearerAuth flag
required for firefly-iii
2022-08-25 16:12:42 +02:00
Girish Ramakrishnan e21f39bc0b Update mail container for quota support 2022-08-23 18:48:06 +02:00
Johannes Zellner 84ca85b315 Ensure app services like redis to be also started on restart if previously stopped 2022-08-23 11:41:08 +02:00
Girish Ramakrishnan d1bdb80c72 Update mail container for quota support 2022-08-22 19:03:47 +02:00
Johannes Zellner d20f8d5e75 Fix acme refactoring 2022-08-22 12:55:43 +02:00
Johannes Zellner b2de6624fd Make email actions buttons 2022-08-21 12:22:53 +02:00
Girish Ramakrishnan 1591541c7f mail: allow aliases to have wildcard
this came out of https://forum.cloudron.io/topic/6350/disposable-email-prefixes-for-existing-mailboxes/
2022-08-18 15:22:00 +02:00
Girish Ramakrishnan 6124323d52 improve mailbox.update 2022-08-18 12:38:46 +02:00
Girish Ramakrishnan b23189b45c mail: quota support 2022-08-18 11:31:40 +02:00
Girish Ramakrishnan 1c18c16e38 typo 2022-08-15 21:09:25 +02:00
Girish Ramakrishnan d07b1c7280 directoryServer: move out start/stop from cron 2022-08-15 21:08:22 +02:00
Girish Ramakrishnan 20d722f076 Fix test 2022-08-15 20:45:55 +02:00
Girish Ramakrishnan bb3be9f380 style 2022-08-15 20:45:55 +02:00
Girish Ramakrishnan edd284fe0b rename user directory to directory server 2022-08-15 20:45:51 +02:00
Girish Ramakrishnan b5cc7d90a9 Fix crash when cron seed file is missing 2022-08-10 22:07:05 +02:00
Girish Ramakrishnan 251c1f9757 add readOnly attribute check for port bindings 2022-08-10 14:22:31 +02:00
Girish Ramakrishnan 03cd9bcc7c Update readOnly flag to tcpPorts and udpPorts 2022-08-10 13:57:00 +02:00
Johannes Zellner fc8572c2af Raise alert for when an app cannot be autoupdated 2022-08-10 12:19:54 +02:00
Johannes Zellner a913660aeb Ensure we have a BoxError here 2022-08-10 12:19:54 +02:00
Girish Ramakrishnan 9c82765512 parseInt returns NaN on failure 2022-08-08 20:33:41 +02:00
Johannes Zellner ace96bd228 Fix stringification for debug of taskError object if set 2022-08-08 13:12:53 +02:00
Johannes Zellner 02d95810a6 Do not include proxy apps in graphs 2022-08-05 14:38:57 +02:00
Johannes Zellner 0fcb202364 Expose groups as memberof in ldap and userdirectory 2022-08-04 11:22:16 +02:00
Johannes Zellner 88eb809c6e For ldap users created on first login, make sure we also check 2fa if enabled 2022-08-03 18:20:43 +02:00
Johannes Zellner 1534eaf6f7 Fixup applink tests 2022-08-03 14:57:58 +02:00
Johannes Zellner a2a60ff426 Add support for LDAP cn=...+totptoken=.. support 2022-08-02 15:27:34 +02:00
Johannes Zellner afc70ac332 Expose twoFactorAuthenticationEnabled state of users via user directory 2022-08-02 15:27:34 +02:00
Girish Ramakrishnan d5e5b64df2 cloudron-setup/motd: show ipv4 or ipv6 setup link 2022-08-01 18:32:07 +02:00
Girish Ramakrishnan 4a18ecc0ef unbound: enable ip6 2022-08-01 14:15:09 +02:00
Girish Ramakrishnan f355403412 npm: make it work with ipv6 only servers 2022-08-01 14:15:09 +02:00
Girish Ramakrishnan 985320d355 switch registry url based on ipv6 availability 2022-08-01 14:15:09 +02:00
Girish Ramakrishnan 26c9d8bc88 notification: Fix crash when backupId is null 2022-08-01 14:15:09 +02:00
Girish Ramakrishnan 2b81163179 add to changes 2022-07-30 13:16:19 +02:00
Johannes Zellner 6715efca50 Distinguish ghost/impersonate logins from others 2022-07-29 20:39:18 +02:00
Johannes Zellner 612b1d6030 Also remove the virtual user and admin groups for userdirectory 2022-07-29 11:17:31 +02:00
Johannes Zellner b71254a0c3 Remove virtual user and admin groups to ldap user records 2022-07-29 11:11:53 +02:00
Johannes Zellner c0e5f60592 Also stash random minute cron tick in seed file 2022-07-29 09:15:42 +02:00
Girish Ramakrishnan 64243425ce installer: suppress VERSION not found error 2022-07-27 06:16:27 +02:00
Girish Ramakrishnan 9ad7fda3cd ubuntu: do not explicitly disable ipv6
IIRC, we had this because unbound will not start up on servers with IPv6 disabled (in the kernel).
Maybe this is a thing of the past by now.
2022-07-27 06:16:03 +02:00
Girish Ramakrishnan c0eedc97ac collectd: always disable FQDNLookup 2022-07-25 17:01:49 +02:00
Johannes Zellner 5b4a1e0ec1 Make certificate cron job more predictable with persistent hourly seed 2022-07-25 15:40:49 +02:00
Johannes Zellner 5b31486dc9 Randomize certificate renewal check over a whole day 2022-07-22 19:32:43 +02:00
Girish Ramakrishnan 116cde19f9 constants: location -> subdomain 2022-07-14 15:18:17 +05:30
Girish Ramakrishnan 14fc089f05 Fixup user and acme cert syncing 2022-07-14 15:04:45 +05:30
Girish Ramakrishnan 885d60f7cc reverseproxy: add setUserCertificate 2022-07-14 13:25:41 +05:30
Girish Ramakrishnan d33fd7b886 do not use bundle terminology
apparently, bundle is also like a cert chain
2022-07-14 12:39:41 +05:30
Girish Ramakrishnan ba067a959c reverseproxy: per location user certificates 2022-07-14 12:21:30 +05:30
Girish Ramakrishnan a246cb7e73 return location certificates 2022-07-14 11:57:04 +05:30
Girish Ramakrishnan f0abd7edc8 certificateJson can be null 2022-07-14 10:52:31 +05:30
Girish Ramakrishnan 127470ae59 domains: fix error handling 2022-07-14 10:35:59 +05:30
Girish Ramakrishnan efac46e40e verifyDomainConfig: just throw the error 2022-07-14 10:32:30 +05:30
Girish Ramakrishnan 6ab237034d remove superfluous validation 2022-07-13 12:06:48 +05:30
Girish Ramakrishnan 2af29fd844 cleanupCerts: add progress 2022-07-13 11:22:47 +05:30
Girish Ramakrishnan 1549f6a4d0 fix various terminology in code
subdomain, domain - strings
location - { subdomain, domain }
bundle - { cert, key }
bundlePath - { certFilePath, keyFilePath }

vhost is really just for virtual hosting
fqdn for others
2022-07-13 10:15:09 +05:30
Girish Ramakrishnan 5d16aca8f4 add script to recreate containers 2022-07-12 20:51:51 +05:30
Johannes Zellner 2facc6774b applinks icon improvements 2022-07-08 18:07:52 +02:00
Johannes Zellner e800c7d282 Only list applinks a user has access to 2022-07-08 15:14:48 +02:00
Johannes Zellner a58228952a Support accessRestriction for visibility of applinks 2022-07-07 19:44:59 +02:00
Johannes Zellner 3511856a7c support applink tags 2022-07-07 19:11:47 +02:00
Johannes Zellner 006a53dc7a Do not spam the logs on get queries 2022-07-07 18:56:21 +02:00
Johannes Zellner 45c73798b9 Fixup typo 2022-07-07 18:53:52 +02:00
Johannes Zellner c704884b10 Ensure applink label is a string 2022-07-07 18:53:27 +02:00
Johannes Zellner b54113ade3 Improve applink meta info detection 2022-07-07 18:19:53 +02:00
Johannes Zellner ac00225a75 Support applink update 2022-07-07 16:53:06 +02:00
Johannes Zellner f43fd21929 Better applink icon support 2022-07-07 16:06:04 +02:00
Johannes Zellner 741c21b368 Fixup applink routes 2022-07-07 13:01:23 +02:00
Johannes Zellner 5a26fe7361 Add applinks.js to routes/index 2022-07-07 12:44:12 +02:00
Johannes Zellner 1185dc7f79 Attempt to fetch applink icon and label from page 2022-07-07 12:36:53 +02:00
Johannes Zellner e1ac2b7b00 Add initial applink support 2022-07-06 20:37:52 +02:00
Girish Ramakrishnan e2c6672a5c better wording 2022-07-02 17:16:47 +05:30
Johannes Zellner 5c50534e21 Improve backup cleanup progress message 2022-07-01 14:18:50 +02:00
Girish Ramakrishnan 55e2139c69 restore: encrypted filenames 2022-06-27 09:49:58 -07:00
Johannes Zellner 34ff3462e9 Fixup backup_config migration script 2022-06-27 17:16:04 +02:00
Girish Ramakrishnan 104bdaf76b mail: cgroup v2 detection fix
there is crash in mail container when fts/solr is enabled
2022-06-26 14:28:22 -07:00
Girish Ramakrishnan c9f7b9a8a6 backups: make filename encryption optional 2022-06-26 09:37:22 -07:00
Girish Ramakrishnan 2e5d89be6b allow space in backup label 2022-06-24 09:18:51 -07:00
Girish Ramakrishnan bcf474aab6 redis: rebuild 2022-06-23 15:52:59 -07:00
Girish Ramakrishnan dea74f05ab remove bogus logic
db-migrate always runs a migration in a transaction. so no volume
was created in case of a failure
2022-06-23 10:31:13 -07:00
Girish Ramakrishnan 69e0f2f727 7.2.5 changes
(cherry picked from commit 131f823e57)
2022-06-23 10:27:57 -07:00
Girish Ramakrishnan 080f701f33 hetzner: debug typo 2022-06-22 22:12:19 -07:00
Girish Ramakrishnan 94a196bfa0 Fix issue where only 25 group members were returned
This is because GROUP_CONCAT defaults to 1024. uuid is 40 chars.
1024/40 = ~25
2022-06-22 17:54:52 -07:00
Girish Ramakrishnan 3a63158763 rename function to setMembers 2022-06-22 17:36:19 -07:00
Girish Ramakrishnan d9c47efe1f Fix storage volume migration
Patch the migration so it runs again properly in 7.2.5

https://forum.cloudron.io/topic/7256/app-data-regression-in-v7-2-4
(cherry picked from commit c2fdb9ae3f)
2022-06-22 17:16:47 -07:00
Johannes Zellner e818e5f7d5 Reload volumes in case one was created in the for loop 2022-06-22 15:32:50 +02:00
Girish Ramakrishnan cac0933334 typo 2022-06-13 13:55:04 -07:00
Girish Ramakrishnan b74f01bb9e clourdon-setup: memory keeps going lower 2022-06-13 10:58:55 -07:00
Girish Ramakrishnan 1f2d596a4a 7.2.4 changes
(cherry picked from commit 61a1ac6983)
2022-06-10 13:31:46 -07:00
Girish Ramakrishnan ce06b2e150 Fix upstreamUri validation 2022-06-10 11:23:58 -07:00
Girish Ramakrishnan 9bd9b72e5d apphealthmonitor: Fix crash 2022-06-10 11:09:41 -07:00
Girish Ramakrishnan a32166bc9d data dir: allow sameness of old and new dir
this makes it easy to migrate to a new volume setup
2022-06-09 17:49:33 -07:00
Johannes Zellner f382b8f1f5 Set real upstreamUri for healthcheck 2022-06-09 15:04:09 +02:00
Johannes Zellner fbc7fcf04b Put healthcheck errors in app logs 2022-06-09 14:56:40 +02:00
Johannes Zellner 11d7dfa071 Accept upstreamUri as string for proxy app install 2022-06-09 14:35:05 +02:00
Johannes Zellner 923a9f6560 Rename RELAY_APPSTORE_ID to PROXY_APP_APPSTORE_ID 2022-06-09 13:57:57 +02:00
Johannes Zellner 25f44f58e3 Start task also needs to skip container starting for proxy app 2022-06-09 10:48:54 +02:00
Johannes Zellner d55a6a5eec Update reverse proxy app config on upstreamUri change 2022-06-09 10:48:54 +02:00
Johannes Zellner f854d86986 Use upstreamUri in reverseproxy config 2022-06-09 10:48:54 +02:00
Johannes Zellner 6a7379e64c Add apps.upstreamUri support 2022-06-09 10:48:54 +02:00
Johannes Zellner a955457ee7 Support proxy app 2022-06-09 10:48:54 +02:00
117 changed files with 3185 additions and 1338 deletions
+41
View File
@@ -2508,3 +2508,44 @@
* Fix issue where only 25 group members were returned
* Fix eventlog display
[7.3.0]
* Proxied apps
* Applinks - app bookmarks in dashboard
* backups: optional encryption of backup file names
* eventlog: add event for impersonated user login
* ldap & user directory: Remove virtual user and admin groups
* Randomize certificate generation cronjob to lighten load on Let's Encrypt servers
* mail: catch all address can be any domain
* mail: accept only STARTTLS servers for relay
* graphs: cgroup v2 support
* mail: fix issue where signature was appended to text attachments
* redis: restart button will now rebuild if the container is missing
* backups: allow space in label name
* mail: fix crash when solr is enabled on Ubuntu 22 (cgroup v2 detection fix)
* mail: fix issue where certificate renewal did not restart the mail container properly
* notification: Fix crash when backupId is null
* IPv6: initial support for ipv6 only server
* User directory: Cloudron connector uses 2FA auth
* port bindings: add read only flag
* mail: add storage quota support
* mail: allow aliases to have wildcard
* proxyAuth: add supportsBearerAuth flag
* backups: Fix precondition check which was not erroring if mount is missing
* mail: add queue management API and UI
* graphs: show app disk usage graphs
* UI: fix issue where mailbox display name was not init correctly
* wasabi: add singapore and sydney regions
* filemanager: add split view
* nginx: fix zero length certs when out of disk space
* read only API tokens
[7.3.1]
* Add cloudlare R2
* app proxy: fixes to https proxying
* app links: fix icons
[7.3.2]
* support: require owner permissions
* postgresql: fix issue when restoring large dumps
* graphs: add cpu/disk/network usage
* graphs: new disk usage UI
+5 -5
View File
@@ -9,7 +9,7 @@ const fs = require('fs'),
safe = require('safetydance'),
server = require('./src/server.js'),
settings = require('./src/settings.js'),
userdirectory = require('./src/userdirectory.js');
directoryServer = require('./src/directoryserver.js');
let logFd;
@@ -38,8 +38,8 @@ async function startServers() {
await proxyAuth.start();
await ldap.start();
const conf = await settings.getUserDirectoryConfig();
if (conf.enabled) await userdirectory.start();
const conf = await settings.getDirectoryServerConfig();
if (conf.enabled) await directoryServer.start();
}
async function main() {
@@ -54,7 +54,7 @@ async function main() {
await proxyAuth.stop();
await server.stop();
await userdirectory.stop();
await directoryServer.stop();
await ldap.stop();
setTimeout(process.exit.bind(process), 3000);
});
@@ -64,7 +64,7 @@ async function main() {
await proxyAuth.stop();
await server.stop();
await userdirectory.stop();
await directoryServer.stop();
await ldap.stop();
setTimeout(process.exit.bind(process), 3000);
});
@@ -21,11 +21,6 @@ exports.up = async function(db) {
const apps = await db.runSql('SELECT * FROM apps WHERE dataDir IS NOT NULL');
for (const app of apps) {
if (app.storageVolumeId) {
console.log(`data-dir (${app.id}): app was migrated in 7.2.4`);
continue;
}
const allVolumes = await db.runSql('SELECT * FROM volumes');
console.log(`data-dir (${app.id}): migrating data dir ${app.dataDir}`);
@@ -0,0 +1,9 @@
'use strict';
exports.up = async function (db) {
await db.runSql('ALTER TABLE apps ADD COLUMN upstreamUri VARCHAR(256) DEFAULT ""');
};
exports.down = async function (db) {
await db.runSql('ALTER TABLE apps DROP COLUMN upstreamUri');
};
@@ -0,0 +1,15 @@
'use strict';
exports.up = async function(db) {
const result = await db.runSql('SELECT * FROM settings WHERE name=?', [ 'backup_config' ]);
if (!result.length) return;
const backupConfig = JSON.parse(result[0].value);
if (backupConfig.encryption && backupConfig.format === 'rsync') backupConfig.encryptedFilenames = true;
await db.runSql('UPDATE settings SET value=? WHERE name=?', [ JSON.stringify(backupConfig), 'backup_config', ]);
};
exports.down = async function(/* db */) {
};
@@ -0,0 +1,22 @@
'use strict';
exports.up = async function (db) {
var cmd = 'CREATE TABLE applinks(' +
'id VARCHAR(128) NOT NULL UNIQUE,' +
'accessRestrictionJson TEXT,' +
'creationTime TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,' +
'updateTime TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,' +
'ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,' +
'label VARCHAR(128),' +
'tagsJson VARCHAR(2048),' +
'icon MEDIUMBLOB,' +
'upstreamUri VARCHAR(256) DEFAULT "",' +
'PRIMARY KEY (id)) CHARACTER SET utf8 COLLATE utf8_bin';
await db.runSql(cmd);
};
exports.down = async function (db) {
await db.runSql('DROP TABLE applinks');
};
@@ -0,0 +1,17 @@
'use strict';
const async = require('async');
exports.up = function(db, callback) {
async.series([
db.runSql.bind(db, 'ALTER TABLE mailboxes ADD COLUMN storageQuota BIGINT DEFAULT 0'),
db.runSql.bind(db, 'ALTER TABLE mailboxes ADD COLUMN messagesQuota BIGINT DEFAULT 0'),
], callback);
};
exports.down = function(db, callback) {
async.series([
db.runSql.bind(db, 'ALTER TABLE mailboxes DROP COLUMN storageQuota'),
db.runSql.bind(db, 'ALTER TABLE mailboxes DROP COLUMN messagesQuota')
], callback);
};
@@ -0,0 +1,18 @@
'use strict';
const safe = require('safetydance');
exports.up = async function (db) {
const mailDomains = await db.runSql('SELECT * FROM mail', []);
for (const mailDomain of mailDomains) {
let catchAll = safe.JSON.parse(mailDomain.catchAllJson) || [];
if (catchAll.length === 0) continue;
catchAll = catchAll.map(a => `${a}@${mailDomain.domain}`);
await db.runSql('UPDATE mail SET catchAllJson = ? WHERE domain = ?', [ JSON.stringify(catchAll), mailDomain.domain ]);
}
};
exports.down = async function( /* db */) {
};
@@ -0,0 +1,13 @@
'use strict';
exports.up = async function (db) {
await db.runSql('ALTER TABLE tokens DROP COLUMN scope');
await db.runSql('ALTER TABLE tokens ADD COLUMN scopeJson TEXT');
await db.runSql('UPDATE tokens SET scopeJson = ?', [ JSON.stringify({'*':'rw'})]);
};
exports.down = async function (db) {
await db.runSql('ALTER TABLE tokens ADD COLUMN scope VARCHAR(512) NOT NULL DEFAULT ""');
await db.runSql('ALTER TABLE tokens DROP COLUMN scopeJson');
};
+17 -1
View File
@@ -58,7 +58,7 @@ CREATE TABLE IF NOT EXISTS tokens(
accessToken VARCHAR(128) NOT NULL UNIQUE,
identifier VARCHAR(128) NOT NULL, // resourceId: app id or user id
clientId VARCHAR(128),
scope VARCHAR(512) NOT NULL,
scopeJson TEXT,
expires BIGINT NOT NULL, // FIXME: make this a timestamp
lastUsedTime TIMESTAMP NULL,
PRIMARY KEY(accessToken));
@@ -102,6 +102,7 @@ CREATE TABLE IF NOT EXISTS apps(
appStoreIcon MEDIUMBLOB,
icon MEDIUMBLOB,
crontab TEXT,
upstreamUri VARCHAR(256) DEFAULT "",
FOREIGN KEY(mailboxDomain) REFERENCES domains(domain),
FOREIGN KEY(taskId) REFERENCES tasks(id),
@@ -216,6 +217,8 @@ CREATE TABLE IF NOT EXISTS mailboxes(
domain VARCHAR(128),
active BOOLEAN DEFAULT 1,
enablePop3 BOOLEAN DEFAULT 0,
storageQuota BIGINT DEFAULT 0,
messagesQuota BIGINT DEFAULT 0,
FOREIGN KEY(domain) REFERENCES mail(domain),
FOREIGN KEY(aliasDomain) REFERENCES mail(domain),
@@ -297,4 +300,17 @@ CREATE TABLE IF NOT EXISTS blobs(
value MEDIUMBLOB,
PRIMARY KEY(id));
CREATE TABLE IF NOT EXISTS appLinks(
id VARCHAR(128) NOT NULL UNIQUE,
accessRestrictionJson TEXT, // { users: [ ], groups: [ ] }
creationTime TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, // when the app was installed
updateTime TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, // when the last app update was done
ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, // when this db record was updated (useful for UI caching)
label VARCHAR(128), // display name
tagsJson VARCHAR(2048), // array of tags
icon MEDIUMBLOB,
upstreamUri VARCHAR(256) DEFAULT "",
PRIMARY KEY(id));
CHARACTER SET utf8 COLLATE utf8_bin;
+840 -147
View File
File diff suppressed because it is too large Load Diff
+3 -3
View File
@@ -18,7 +18,7 @@
"aws-sdk": "^2.1115.0",
"basic-auth": "^2.0.1",
"body-parser": "^1.20.0",
"cloudron-manifestformat": "^5.16.0",
"cloudron-manifestformat": "^5.18.0",
"connect": "^3.7.0",
"connect-lastmile": "^2.1.1",
"connect-timeout": "^1.9.0",
@@ -34,6 +34,7 @@
"express": "^4.17.3",
"ipaddr.js": "^2.0.1",
"js-yaml": "^4.1.0",
"jsdom": "^20.0.0",
"json": "^11.0.0",
"jsonwebtoken": "^8.5.1",
"ldapjs": "^2.3.2",
@@ -44,7 +45,6 @@
"multiparty": "^4.2.3",
"mysql": "^2.18.1",
"nodemailer": "^6.7.3",
"nodemailer-smtp-transport": "^2.7.4",
"progress-stream": "^2.0.0",
"qrcode": "^1.5.0",
"readdirp": "^3.6.0",
@@ -74,7 +74,7 @@
"nyc": "^15.1.0"
},
"scripts": {
"test": "./runTests",
"test": "./run-tests",
"postmerge": "/bin/true",
"precommit": "/bin/true",
"prepush": "npm test",
+2 -2
View File
@@ -6,7 +6,7 @@ readonly source_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly DATA_DIR="${HOME}/.cloudron_test"
readonly DEFAULT_TESTS="./src/test/*-test.js ./src/routes/test/*-test.js"
! "${source_dir}/src/test/checkInstall" && exit 1
! "${source_dir}/src/test/check-install" && exit 1
# cleanup old data dirs some of those docker container data requires sudo to be removed
echo "=> Provide root password to purge any leftover data in ${DATA_DIR} and load apparmor profile:"
@@ -39,7 +39,7 @@ if [[ -z ${FAST+x} ]]; then
echo "=> Delete all docker containers first"
docker ps -qa --filter "label=isCloudronManaged" | xargs --no-run-if-empty docker rm -f
docker rm -f mysql-server
echo "==> To skip this run with: FAST=1 ./runTests"
echo "==> To skip this run with: FAST=1 ./run-tests"
else
echo "==> WARNING!! Skipping docker container cleanup, the database might not be pristine!"
fi
+19 -8
View File
@@ -11,7 +11,7 @@ trap exitHandler EXIT
# change this to a hash when we make a upgrade release
readonly LOG_FILE="/var/log/cloudron-setup.log"
readonly MINIMUM_DISK_SIZE_GB="18" # this is the size of "/" and required to fit in docker images 18 is a safe bet for different reporting on 20GB min
readonly MINIMUM_MEMORY="974" # this is mostly reported for 1GB main memory (DO 992, EC2 990, Linode 989, Serverdiscounter.com 974)
readonly MINIMUM_MEMORY="960" # this is mostly reported for 1GB main memory (DO 992, EC2 967, Linode 989, Serverdiscounter.com 974)
readonly curl="curl --fail --connect-timeout 20 --retry 10 --retry-delay 2 --max-time 2400"
@@ -236,20 +236,31 @@ while true; do
sleep 10
done
if ! ip=$(curl -s --fail --connect-timeout 2 --max-time 2 https://ipv4.api.cloudron.io/api/v1/helper/public_ip | sed -n -e 's/.*"ip": "\(.*\)"/\1/p'); then
ip='<IP>'
fi
ip4=$(curl -s --fail --connect-timeout 2 --max-time 2 https://ipv4.api.cloudron.io/api/v1/helper/public_ip | sed -n -e 's/.*"ip": "\(.*\)"/\1/p' || true)
ip6=$(curl -s --fail --connect-timeout 2 --max-time 2 https://ipv6.api.cloudron.io/api/v1/helper/public_ip | sed -n -e 's/.*"ip": "\(.*\)"/\1/p' || true)
url4=""
url6=""
fallbackUrl=""
if [[ -z "${setupToken}" ]]; then
url="https://${ip}"
[[ -n "${ip4}" ]] && url4="https://${ip4}"
[[ -n "${ip6}" ]] && url6="https://[${ip6}]"
[[ -z "${ip4}" && -z "${ip6}" ]] && fallbackUrl="https://<IP>"
else
url="https://${ip}/?setupToken=${setupToken}"
[[ -n "${ip4}" ]] && url4="https://${ip4}/?setupToken=${setupToken}"
[[ -n "${ip6}" ]] && url6="https://[${ip6}]/?setupToken=${setupToken}"
[[ -z "${ip4}" && -z "${ip6}" ]] && fallbackUrl="https://<IP>?setupToken=${setupToken}"
fi
echo -e "\n\n${GREEN}After reboot, visit ${url} and accept the self-signed certificate to finish setup.${DONE}\n"
echo -e "\n\n${GREEN}After reboot, visit one of the following URLs and accept the self-signed certificate to finish setup.${DONE}\n"
[[ -n "${url4}" ]] && echo -e " * ${GREEN}${url4}${DONE}"
[[ -n "${url6}" ]] && echo -e " * ${GREEN}${url6}${DONE}"
[[ -n "${fallbackUrl}" ]] && echo -e " * ${GREEN}${fallbackUrl}${DONE}"
if [[ "${rebootServer}" == "true" ]]; then
systemctl stop box mysql # sometimes mysql ends up having corrupt privilege tables
read -p "The server has to be rebooted to apply all the settings. Reboot now ? [Y/n] " yn
# https://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html#ANSI_002dC-Quoting
read -p $'\n'"The server has to be rebooted to apply all the settings. Reboot now ? [Y/n] " yn
yn=${yn:-y}
case $yn in
[Yy]* ) exitHandler; systemctl reboot;;
+3 -2
View File
@@ -1,6 +1,7 @@
#!/bin/bash
# This script is run on the base ubuntu. Put things here which are managed by ubuntu
# This script is also run after ubuntu upgrade
set -euv -o pipefail
@@ -120,13 +121,13 @@ else
if ! apt-get install -y --no-install-recommends collectd collectd-utils; then
# FQDNLookup is true in default debian config. The box code has a custom collectd.conf that fixes this
echo "Failed to install collectd, continuing anyway. Presumably because of http://mailman.verplant.org/pipermail/collectd/2015-March/006491.html"
sed -e 's/^FQDNLookup true/FQDNLookup false/' -i /etc/collectd/collectd.conf
fi
if [[ "${ubuntu_version}" == "20.04" ]]; then
echo -e "\nLD_PRELOAD=/usr/lib/python3.8/config-3.8-x86_64-linux-gnu/libpython3.8.so" >> /etc/default/collectd
fi
fi
sed -e 's/^FQDNLookup true/FQDNLookup false/' -i /etc/collectd/collectd.conf
# some hosts like atlantic install ntp which conflicts with timedatectl. https://serverfault.com/questions/1024770/ubuntu-20-04-time-sync-problems-and-possibly-incorrect-status-information
echo "==> Configuring host"
@@ -179,7 +180,7 @@ systemctl disable systemd-resolved || true
ufw disable || true
# we need unbound to work as this is required for installer.sh to do any DNS requests
echo -e "server:\n\tinterface: 127.0.0.1\n\tdo-ip6: no" > /etc/unbound/unbound.conf.d/cloudron-network.conf
echo -e "server:\n\tinterface: 127.0.0.1\n" > /etc/unbound/unbound.conf.d/cloudron-network.conf
systemctl restart unbound
# Ubuntu 22 has private home directories by default (https://discourse.ubuntu.com/t/private-home-directories-for-ubuntu-21-04-onwards/)
+11 -4
View File
@@ -69,7 +69,7 @@ readonly ubuntu_codename=$(lsb_release -cs)
readonly is_update=$(systemctl is-active -q box && echo "yes" || echo "no")
log "Updating from $(cat $box_src_dir/VERSION) to $(cat $box_src_tmp_dir/VERSION)"
log "Updating from $(cat $box_src_dir/VERSION 2>/dev/null) to $(cat $box_src_tmp_dir/VERSION 2>/dev/null)"
# https://docs.docker.com/engine/installation/linux/ubuntulinux/
readonly docker_version=20.10.14
@@ -145,12 +145,18 @@ log "downloading new addon images"
images=$(node -e "let i = require('${box_src_tmp_dir}/src/infra_version.js'); console.log(i.baseImages.map(function (x) { return x.tag; }).join(' '), Object.keys(i.images).map(function (x) { return i.images[x].tag; }).join(' '));")
log "\tPulling docker images: ${images}"
if ! curl -s --fail --connect-timeout 2 --max-time 2 https://ipv4.api.cloudron.io/api/v1/helper/public_ip; then
docker_registry=registry.ipv6.docker.com
else
docker_registry=registry-1.docker.io
fi
for image in ${images}; do
while ! docker pull "${image}"; do # this pulls the image using the sha256
while ! docker pull "${docker_registry}/${image}"; do # this pulls the image using the sha256
log "Could not pull ${image}"
sleep 5
done
while ! docker pull "${image%@sha256:*}"; do # this will tag the image for readability
while ! docker pull "${docker_registry}/${image%@sha256:*}"; do # this will tag the image for readability
log "Could not pull ${image%@sha256:*}"
sleep 5
done
@@ -163,7 +169,8 @@ CLOUDRON_SYSLOG_VERSION="1.1.0"
while [[ ! -f "${CLOUDRON_SYSLOG}" || "$(${CLOUDRON_SYSLOG} --version)" != ${CLOUDRON_SYSLOG_VERSION} ]]; do
rm -rf "${CLOUDRON_SYSLOG_DIR}"
mkdir -p "${CLOUDRON_SYSLOG_DIR}"
if npm install --unsafe-perm -g --prefix "${CLOUDRON_SYSLOG_DIR}" cloudron-syslog@${CLOUDRON_SYSLOG_VERSION}; then break; fi
# verbatim is not needed in node 18 since that is the default there. in node 16, ipv4 is preferred and this breaks on ipv6 only servers
if NODE_OPTIONS="--dns-result-order=verbatim" npm install --unsafe-perm -g --prefix "${CLOUDRON_SYSLOG_DIR}" cloudron-syslog@${CLOUDRON_SYSLOG_VERSION}; then break; fi
log "Failed to install cloudron-syslog, trying again"
sleep 5
done
+32
View File
@@ -0,0 +1,32 @@
#!/bin/bash
set -eu -o pipefail
readonly logfile="/home/yellowtent/platformdata/logs/box.log"
if [[ ${EUID} -ne 0 ]]; then
echo "This script should be run as root." > /dev/stderr
exit 1
fi
echo "This will re-create all the containers. Services will go down for a bit."
read -p "Do you want to proceed? (y/N) " -n 1 -r choice
echo
if [[ ! $choice =~ ^[Yy]$ ]]; then
exit 1
fi
echo -n "Re-creating addon containers (this takes a while) ."
line_count=$(cat /home/yellowtent/platformdata/logs/box.log | wc -l)
sed -e 's/"version": ".*",/"version":"48.0.0",/' -i /home/yellowtent/platformdata/INFRA_VERSION
systemctl restart box
while ! tail -n "+${line_count}" "${logfile}" | grep -q "platform is ready"; do
echo -n "."
sleep 2
done
echo -e "\nDone.\nThe Cloudron dashboard will say 'Configuring (Queued)' for each app. The apps will come up in a short while."
+2 -2
View File
@@ -59,7 +59,7 @@ mkdir -p "${PLATFORM_DATA_DIR}/mongodb"
mkdir -p "${PLATFORM_DATA_DIR}/redis"
mkdir -p "${PLATFORM_DATA_DIR}/addons/mail/banner" \
"${PLATFORM_DATA_DIR}/addons/mail/dkim"
mkdir -p "${PLATFORM_DATA_DIR}/collectd/collectd.conf.d"
mkdir -p "${PLATFORM_DATA_DIR}/collectd"
mkdir -p "${PLATFORM_DATA_DIR}/logrotate.d"
mkdir -p "${PLATFORM_DATA_DIR}/acme"
mkdir -p "${PLATFORM_DATA_DIR}/backup"
@@ -133,7 +133,7 @@ rm -f /etc/sudoers.d/${USER} /etc/sudoers.d/cloudron
cp "${script_dir}/start/sudoers" /etc/sudoers.d/cloudron
log "Configuring collectd"
rm -rf /etc/collectd /var/log/collectd.log
rm -rf /etc/collectd /var/log/collectd.log "${PLATFORM_DATA_DIR}/collectd/collectd.conf.d"
ln -sfF "${PLATFORM_DATA_DIR}/collectd" /etc/collectd
cp "${script_dir}/start/collectd/collectd.conf" "${PLATFORM_DATA_DIR}/collectd/collectd.conf"
systemctl restart collectd
+33 -12
View File
@@ -4,30 +4,51 @@
printf "**********************************************************************\n\n"
cache_file="/var/cache/cloudron-motd-cache"
readonly cache_file4="/var/cache/cloudron-motd-cache4"
readonly cache_file6="/var/cache/cloudron-motd-cache6"
if [[ -z "$(ls -A /home/yellowtent/platformdata/addons/mail/dkim)" ]]; then
if [[ ! -f "${cache_file}" ]]; then
curl --fail --connect-timeout 2 --max-time 2 -q https://ipv4.api.cloudron.io/api/v1/helper/public_ip --output "${cache_file}" || true
fi
if [[ -f "${cache_file}" ]]; then
ip=$(sed -n -e 's/.*"ip": "\(.*\)"/\1/p' /var/cache/cloudron-motd-cache)
url4=""
url6=""
fallbackUrl=""
function detectIp() {
if [[ ! -f "${cache_file4}" ]]; then
ip4=$(curl -s --fail --connect-timeout 2 --max-time 2 https://ipv4.api.cloudron.io/api/v1/helper/public_ip | sed -n -e 's/.*"ip": "\(.*\)"/\1/p' || true)
[[ -n "${ip4}" ]] && echo "${ip4}" > "${cache_file4}"
else
ip='<IP>'
ip4=$(cat "${cache_file4}")
fi
if [[ ! -f "${cache_file6}" ]]; then
ip6=$(curl -s --fail --connect-timeout 2 --max-time 2 https://ipv6.api.cloudron.io/api/v1/helper/public_ip | sed -n -e 's/.*"ip": "\(.*\)"/\1/p' || true)
[[ -n "${ip6}" ]] && echo "${ip6}" > "${cache_file6}"
else
ip6=$(cat "${cache_file6}")
fi
if [[ ! -f /etc/cloudron/SETUP_TOKEN ]]; then
url="https://${ip}"
[[ -n "${ip4}" ]] && url4="https://${ip4}"
[[ -n "${ip6}" ]] && url6="https://[${ip6}]"
[[ -z "${ip4}" && -z "${ip6}" ]] && fallbackUrl="https://<IP>"
else
setupToken="$(cat /etc/cloudron/SETUP_TOKEN)"
url="https://${ip}/?setupToken=${setupToken}"
[[ -n "${ip4}" ]] && url4="https://${ip4}/?setupToken=${setupToken}"
[[ -n "${ip6}" ]] && url6="https://[${ip6}]/?setupToken=${setupToken}"
[[ -z "${ip4}" && -z "${ip6}" ]] && fallbackUrl="https://<IP>?setupToken=${setupToken}"
fi
}
if [[ -z "$(ls -A /home/yellowtent/platformdata/addons/mail/dkim)" ]]; then
detectIp
printf "\t\t\tWELCOME TO CLOUDRON\n"
printf "\t\t\t-------------------\n"
printf '\n\e[1;32m%-6s\e[m\n\n' "Visit ${url} on your browser and accept the self-signed certificate to finish setup."
printf "Cloudron overview - https://docs.cloudron.io/ \n"
printf '\n\e[1;32m%-6s\e[m\n' "Visit one of the following URLs on your browser and accept the self-signed certificate to finish setup."
[[ -n "${url4}" ]] && printf '\e[1;32m%-6s\e[m\n' " * ${url4}"
[[ -n "${url6}" ]] && printf '\e[1;32m%-6s\e[m\n' " * ${url6}"
[[ -n "${fallbackUrl}" ]] && printf '\e[1;32m%-6s\e[m\n' " * ${fallbackUrl}"
printf "\nCloudron overview - https://docs.cloudron.io/ \n"
printf "Cloudron setup - https://docs.cloudron.io/installation/#setup \n"
else
printf "\t\t\tNOTE TO CLOUDRON ADMINS\n"
+3 -22
View File
@@ -187,9 +187,9 @@ LoadPlugin swap
CalculateNum false
CalculateSum true
CalculateAverage true
CalculateAverage false
CalculateMinimum false
CalculateMaximum true
CalculateMaximum false
CalculateStddev false
</Aggregation>
</Plugin>
@@ -211,23 +211,7 @@ LoadPlugin swap
Interactive false
Import "df"
Import "du"
<Module du>
<Path>
Instance maildata
Dir "/home/yellowtent/boxdata/mail"
</Path>
<Path>
Instance boxdata
Dir "/home/yellowtent/boxdata"
Exclude "mail"
</Path>
<Path>
Instance platformdata
Dir "/home/yellowtent/platformdata"
</Path>
</Module>
Import "docker-stats"
</Plugin>
<Plugin write_graphite>
@@ -243,6 +227,3 @@ LoadPlugin swap
</Node>
</Plugin>
<Include "/etc/collectd/collectd.conf.d">
Filter "*.conf"
</Include>
+64
View File
@@ -0,0 +1,64 @@
import collectd,os,subprocess,json,re
# https://blog.dbrgn.ch/2017/3/10/write-a-collectd-python-plugin/
def parseSiSize(size):
units = {"B": 1, "KB": 10**3, "MB": 10**6, "GB": 10**9, "TB": 10**12}
number, unit, _ = re.split('([a-zA-Z]+)', size.upper())
return int(float(number)*units[unit])
def parseBinarySize(size):
units = {"B": 1, "KIB": 2**10, "MIB": 2**20, "GIB": 2**30, "TIB": 2**40}
number, unit, _ = re.split('([a-zA-Z]+)', size.upper())
return int(float(number)*units[unit])
def init():
collectd.info('custom docker-status plugin initialized')
def read():
try:
lines = subprocess.check_output('docker stats --format "{{ json . }}" --no-stream --no-trunc', shell=True).decode('utf-8').strip().split("\n")
except Exception as e:
collectd.info('\terror getting docker stats: %s' % (str(e)))
return 0
# Sample line
# {"BlockIO":"430kB / 676kB","CPUPerc":"0.00%","Container":"7eae5e6f4f11","ID":"7eae5e6f4f11","MemPerc":"59.15%","MemUsage":"45.55MiB / 77MiB","Name":"1062eef3-ec96-4d81-9f02-15b7dd81ccb9","NetIO":"1.5MB / 3.48MB","PIDs":"5"}
for line in lines:
stat = json.loads(line)
containerName = stat["Name"] # same as app id
networkData = stat["NetIO"].split("/")
networkRead = parseSiSize(networkData[0].strip())
networkWrite = parseSiSize(networkData[1].strip())
blockData = stat["BlockIO"].split("/")
blockRead = parseSiSize(blockData[0].strip())
blockWrite = parseSiSize(blockData[1].strip())
memUsageData = stat["MemUsage"].split("/")
memUsed = parseBinarySize(memUsageData[0].strip())
memMax = parseBinarySize(memUsageData[1].strip())
cpuPercData = stat["CPUPerc"].strip("%")
cpuPerc = float(cpuPercData)
# type comes from https://github.com/collectd/collectd/blob/master/src/types.db and https://collectd.org/wiki/index.php/Data_source
val = collectd.Values(type='gauge', plugin='docker-stats', plugin_instance=containerName)
val.dispatch(values=[networkRead], type_instance='network-read')
val.dispatch(values=[networkWrite], type_instance='network-write')
val.dispatch(values=[blockRead], type_instance='blockio-read')
val.dispatch(values=[blockWrite], type_instance='blockio-write')
val.dispatch(values=[memUsed], type_instance='mem-used')
val.dispatch(values=[memMax], type_instance='mem-max')
val.dispatch(values=[cpuPerc], type_instance='cpu-perc')
val = collectd.Values(type='counter', plugin='docker-stats', plugin_instance=containerName)
val.dispatch(values=[networkRead], type_instance='network-read')
val.dispatch(values=[networkWrite], type_instance='network-write')
val.dispatch(values=[blockRead], type_instance='blockio-read')
val.dispatch(values=[blockWrite], type_instance='blockio-write')
collectd.register_init(init)
# see Interval setting in collectd.conf for polling interval
collectd.register_read(read)
-105
View File
@@ -1,105 +0,0 @@
import collectd,os,subprocess,sys,re,time
# https://www.programcreek.com/python/example/106897/collectd.register_read
PATHS = [] # { name, dir, exclude }
# there is a pattern in carbon/storage-schemas.conf which stores values every 12h for a year
INTERVAL = 60 * 60 * 12 # twice a day. change values in docker-graphite if you change this
# we used to pass the INTERVAL as a parameter to register_read. however, collectd write_graphite
# takes a bit to load (tcp connection) and drops the du data. this then means that we have to wait
# for INTERVAL secs for du data. instead, we just cache the value for INTERVAL instead
CACHE = dict()
CACHE_TIME = 0
def du(pathinfo):
# -B1 makes du print block sizes and not apparent sizes (to match df which also uses block sizes)
dirname = pathinfo['dir']
cmd = 'timeout 1800 du -DsB1 "{}"'.format(dirname)
if pathinfo['exclude'] != '':
cmd += ' --exclude "{}"'.format(pathinfo['exclude'])
collectd.info('computing size with command: %s' % cmd);
try:
size = subprocess.check_output(cmd, shell=True).split()[0].decode('utf-8')
collectd.info('\tsize of %s is %s (time: %i)' % (dirname, size, int(time.time())))
return size
except Exception as e:
collectd.info('\terror getting the size of %s: %s' % (dirname, str(e)))
return 0
def parseSize(size):
units = {"B": 1, "KB": 10**3, "MB": 10**6, "GB": 10**9, "TB": 10**12}
number, unit, _ = re.split('([a-zA-Z]+)', size.upper())
return int(float(number)*units[unit])
def dockerSize():
# use --format '{{json .}}' to dump the string. '{{if eq .Type "Images"}}{{.Size}}{{end}}' still creates newlines
# https://godoc.org/github.com/docker/go-units#HumanSize is used. so it's 1000 (KB) and not 1024 (KiB)
cmd = 'timeout 1800 docker system df --format "{{.Size}}" | head -n1'
try:
size = subprocess.check_output(cmd, shell=True).strip().decode('utf-8')
collectd.info('size of docker images is %s (%s) (time: %i)' % (size, parseSize(size), int(time.time())))
return parseSize(size)
except Exception as e:
collectd.info('error getting docker images size : %s' % str(e))
return 0
# configure is called for each module block. this is called before init
def configure(config):
global PATHS
for child in config.children:
if child.key != 'Path':
collectd.info('du plugin: Unknown config key "%s"' % key)
continue
pathinfo = { 'name': '', 'dir': '', 'exclude': '' }
for node in child.children:
if node.key == 'Instance':
pathinfo['name'] = node.values[0]
elif node.key == 'Dir':
pathinfo['dir'] = node.values[0]
elif node.key == 'Exclude':
pathinfo['exclude'] = node.values[0]
PATHS.append(pathinfo);
collectd.info('du plugin: monitoring %s' % pathinfo['dir']);
def init():
global PATHS
collectd.info('custom du plugin initialized with %s %s' % (PATHS, sys.version))
def read():
global CACHE, CACHE_TIME
# read from cache if < 12 hours
read_cache = (time.time() - CACHE_TIME) < INTERVAL
if not read_cache:
CACHE_TIME = time.time()
for pathinfo in PATHS:
dirname = pathinfo['dir']
if read_cache and dirname in CACHE:
size = CACHE[dirname]
else:
size = du(pathinfo)
CACHE[dirname] = size
# type comes from https://github.com/collectd/collectd/blob/master/src/types.db
val = collectd.Values(type='capacity', plugin='du', plugin_instance=pathinfo['name'])
val.dispatch(values=[size], type_instance='usage')
if read_cache and 'docker' in CACHE:
size = CACHE['docker']
else:
size = dockerSize()
CACHE['docker'] = size
val = collectd.Values(type='capacity', plugin='du', plugin_instance='docker')
val.dispatch(values=[size], type_instance='usage')
collectd.register_init(init)
collectd.register_config(configure)
collectd.register_read(read)
+3 -4
View File
@@ -19,9 +19,6 @@ yellowtent ALL=(root) NOPASSWD: /home/yellowtent/box/src/scripts/rmaddondir.sh
Defaults!/home/yellowtent/box/src/scripts/reboot.sh env_keep="HOME BOX_ENV"
yellowtent ALL=(root) NOPASSWD: /home/yellowtent/box/src/scripts/reboot.sh
Defaults!/home/yellowtent/box/src/scripts/configurecollectd.sh env_keep="HOME BOX_ENV"
yellowtent ALL=(root) NOPASSWD: /home/yellowtent/box/src/scripts/configurecollectd.sh
Defaults!/home/yellowtent/box/src/scripts/collectlogs.sh env_keep="HOME BOX_ENV"
yellowtent ALL=(root) NOPASSWD: /home/yellowtent/box/src/scripts/collectlogs.sh
@@ -68,5 +65,7 @@ yellowtent ALL=(root) NOPASSWD: /home/yellowtent/box/src/scripts/rmmount.sh
Defaults!/home/yellowtent/box/src/scripts/remountmount.sh env_keep="HOME BOX_ENV"
yellowtent ALL=(root) NOPASSWD: /home/yellowtent/box/src/scripts/remountmount.sh
cloudron-support ALL=(ALL) NOPASSWD: ALL
Defaults!/home/yellowtent/box/src/scripts/du.sh env_keep="HOME BOX_ENV"
yellowtent ALL=(root) NOPASSWD: /home/yellowtent/box/src/scripts/du.sh
cloudron-support ALL=(ALL) NOPASSWD: ALL
+1 -1
View File
@@ -6,7 +6,7 @@ server:
interface: 127.0.0.1
interface: 172.18.0.1
ip-freebind: yes
do-ip6: no
do-ip6: yes
access-control: 127.0.0.1 allow
access-control: 172.18.0.1/16 allow
cache-max-negative-ttl: 30
-26
View File
@@ -1,26 +0,0 @@
'use strict';
exports = module.exports = {
verifyToken
};
const assert = require('assert'),
BoxError = require('./boxerror.js'),
safe = require('safetydance'),
tokens = require('./tokens.js'),
users = require('./users.js');
async function verifyToken(accessToken) {
assert.strictEqual(typeof accessToken, 'string');
const token = await tokens.getByAccessToken(accessToken);
if (!token) throw new BoxError(BoxError.INVALID_CREDENTIALS, 'No such token');
const user = await users.get(token.identifier);
if (!user) throw new BoxError(BoxError.INVALID_CREDENTIALS, 'User not found');
if (!user.active) throw new BoxError(BoxError.INVALID_CREDENTIALS, 'User not active');
await safe(tokens.update(token.id, { lastUsedTime: new Date() })); // ignore any error
return user;
}
+11 -11
View File
@@ -522,32 +522,32 @@ Acme2.prototype.loadDirectory = async function () {
});
};
Acme2.prototype.getCertificate = async function (vhost, domain, paths) {
assert.strictEqual(typeof vhost, 'string');
Acme2.prototype.getCertificate = async function (fqdn, domain, paths) {
assert.strictEqual(typeof fqdn, 'string');
assert.strictEqual(typeof domain, 'string');
assert.strictEqual(typeof paths, 'object');
debug(`getCertificate: start acme flow for ${vhost} from ${this.caDirectory}`);
debug(`getCertificate: start acme flow for ${fqdn} from ${this.caDirectory}`);
if (vhost !== domain && this.wildcard) { // bare domain is not part of wildcard SAN
vhost = dns.makeWildcard(vhost);
debug(`getCertificate: will get wildcard cert for ${vhost}`);
if (fqdn !== domain && this.wildcard) { // bare domain is not part of wildcard SAN
fqdn = dns.makeWildcard(fqdn);
debug(`getCertificate: will get wildcard cert for ${fqdn}`);
}
await this.loadDirectory();
await this.acmeFlow(vhost, domain, paths);
await this.acmeFlow(fqdn, domain, paths);
};
async function getCertificate(vhost, domain, paths, options) {
assert.strictEqual(typeof vhost, 'string'); // this can also be a wildcard domain (for alias domains)
async function getCertificate(fqdn, domain, paths, options) {
assert.strictEqual(typeof fqdn, 'string'); // this can also be a wildcard domain (for alias domains)
assert.strictEqual(typeof domain, 'string');
assert.strictEqual(typeof paths, 'object');
assert.strictEqual(typeof options, 'object');
await promiseRetry({ times: 3, interval: 0, debug }, async function () {
debug(`getCertificate: for vhost ${vhost} and domain ${domain}`);
debug(`getCertificate: for fqdn ${fqdn} and domain ${domain}`);
const acme = new Acme2(options || { });
return await acme.getCertificate(vhost, domain, paths);
return await acme.getCertificate(fqdn, domain, paths);
});
}
+19 -10
View File
@@ -70,25 +70,36 @@ async function checkAppHealth(app, options) {
const manifest = app.manifest;
const [error, data] = await safe(docker.inspect(app.containerId));
if (error || !data || !data.State) return await setHealth(app, apps.HEALTH_ERROR);
if (data.State.Running !== true) return await setHealth(app, apps.HEALTH_DEAD);
let healthCheckUrl, host;
if (app.manifest.id === constants.PROXY_APP_APPSTORE_ID) {
healthCheckUrl = app.upstreamUri;
host = new URL(app.upstreamUri).host; // includes port
} else {
const [error, data] = await safe(docker.inspect(app.containerId));
if (error || !data || !data.State) return await setHealth(app, apps.HEALTH_ERROR);
if (data.State.Running !== true) return await setHealth(app, apps.HEALTH_DEAD);
// non-appstore apps may not have healthCheckPath
if (!manifest.healthCheckPath) return await setHealth(app, apps.HEALTH_HEALTHY);
// non-appstore apps may not have healthCheckPath
if (!manifest.healthCheckPath) return await setHealth(app, apps.HEALTH_HEALTHY);
healthCheckUrl = `http://${app.containerIp}:${manifest.httpPort}${manifest.healthCheckPath}`;
host = app.fqdn;
}
const healthCheckUrl = `http://${app.containerIp}:${manifest.httpPort}${manifest.healthCheckPath}`;
const [healthCheckError, response] = await safe(superagent
.get(healthCheckUrl)
.set('Host', app.fqdn) // required for some apache configs with rewrite rules
.disableTLSCerts() // for app proxy
.set('Host', host) // required for some apache configs with rewrite rules
.set('User-Agent', 'Mozilla (CloudronHealth)') // required for some apps (e.g. minio)
.redirects(0)
.ok(() => true)
.timeout(options.timeout * 1000));
if (healthCheckError) {
await apps.appendLogLine(app, `=> Healtheck error: ${healthCheckError}`);
await setHealth(app, apps.HEALTH_UNHEALTHY);
} else if (response.status > 403) { // 2xx and 3xx are ok. even 401 and 403 are ok for now (for WP sites)
await apps.appendLogLine(app, `=> Healtheck error got response status ${response.status}`);
await setHealth(app, apps.HEALTH_UNHEALTHY);
} else {
await setHealth(app, apps.HEALTH_HEALTHY);
@@ -129,9 +140,7 @@ async function processDockerEvents(options) {
const [error, info] = await safe(getContainerInfo(containerId));
const program = error ? containerId : (info.addonName || info.app.fqdn);
const now = Date.now();
// do not send mails for dev apps
const notifyUser = !(info.app && info.app.debugMode) && ((now - gLastOomMailTime) > OOM_EVENT_LIMIT);
const notifyUser = !info?.app?.debugMode && ((now - gLastOomMailTime) > OOM_EVENT_LIMIT);
debug(`OOM ${program} notifyUser: ${notifyUser}. lastOomTime: ${gLastOomMailTime} (now: ${now})`);
+210
View File
@@ -0,0 +1,210 @@
'use strict';
exports = module.exports = {
list,
listByUser,
add,
get,
update,
remove,
getIcon
};
const assert = require('assert'),
apps = require('./apps.js'),
BoxError = require('./boxerror.js'),
database = require('./database.js'),
debug = require('debug')('box:applinks'),
jsdom = require('jsdom'),
safe = require('safetydance'),
superagent = require('superagent'),
uuid = require('uuid'),
validator = require('validator');
const APPLINKS_FIELDS= [ 'id', 'accessRestrictionJson', 'creationTime', 'updateTime', 'ts', 'label', 'tagsJson', 'icon', 'upstreamUri' ].join(',');
function postProcess(result) {
assert.strictEqual(typeof result, 'object');
assert(result.tagsJson === null || typeof result.tagsJson === 'string');
result.tags = safe.JSON.parse(result.tagsJson) || [];
delete result.tagsJson;
assert(result.accessRestrictionJson === null || typeof result.accessRestrictionJson === 'string');
result.accessRestriction = safe.JSON.parse(result.accessRestrictionJson);
if (result.accessRestriction && !result.accessRestriction.users) result.accessRestriction.users = [];
delete result.accessRestrictionJson;
result.ts = new Date(result.ts).getTime();
result.icon = result.icon ? result.icon : null;
}
function validateUpstreamUri(upstreamUri) {
assert.strictEqual(typeof upstreamUri, 'string');
if (!upstreamUri) return new BoxError(BoxError.BAD_FIELD, 'upstreamUri cannot be empty');
if (!upstreamUri.includes('://')) return new BoxError(BoxError.BAD_FIELD, 'upstreamUri has no schema');
const uri = safe(() => new URL(upstreamUri));
if (!uri) return new BoxError(BoxError.BAD_FIELD, `upstreamUri is invalid: ${safe.error.message}`);
if (uri.protocol !== 'http:' && uri.protocol !== 'https:') return new BoxError(BoxError.BAD_FIELD, 'upstreamUri has an unsupported scheme');
return null;
}
async function list() {
const results = await database.query(`SELECT ${APPLINKS_FIELDS} FROM applinks ORDER BY upstreamUri`);
results.forEach(postProcess);
return results;
}
async function listByUser(user) {
assert.strictEqual(typeof user, 'object');
const result = await list();
return result.filter((app) => apps.canAccess(app, user));
}
async function detectMetaInfo(applink) {
assert.strictEqual(typeof applink, 'object');
const [error, response] = await safe(superagent.get(applink.upstreamUri).set('User-Agent', 'Mozilla'));
if (error || !response.text) throw new BoxError(BoxError.BAD_FIELD, 'cannot fetch upstream uri for favicon and label');
if (applink.favicon && applink.label) return;
// set redirected URI if any for favicon url
const redirectUri = (response.redirects && response.redirects.length) ? response.redirects[0] : null;
const dom = new jsdom.JSDOM(response.text);
if (!applink.icon) {
let favicon = '';
if (dom.window.document.querySelector('link[rel="apple-touch-icon"]')) favicon = dom.window.document.querySelector('link[rel="apple-touch-icon"]').href ;
if (!favicon.endsWith('.png') && dom.window.document.querySelector('meta[name="msapplication-TileImage"]')) favicon = dom.window.document.querySelector('meta[name="msapplication-TileImage"]').content ;
if (!favicon.endsWith('.png') && dom.window.document.querySelector('link[rel="shortcut icon"]')) favicon = dom.window.document.querySelector('link[rel="shortcut icon"]').href ;
if (!favicon.endsWith('.png') && dom.window.document.querySelector('link[rel="icon"]')) {
let iconElements = dom.window.document.querySelectorAll('link[rel="icon"]');
if (iconElements.length) {
favicon = iconElements[0].href; // choose first one for a start
// check if we have sizes attributes and then choose the largest one
iconElements = Array.from(iconElements).filter(function (e) {
return e.attributes.getNamedItem('sizes') && e.attributes.getNamedItem('sizes').value;
}).sort(function (a, b) {
return parseInt(b.attributes.getNamedItem('sizes').value.split('x')[0]) - parseInt(a.attributes.getNamedItem('sizes').value.split('x')[0]);
});
if (iconElements.length) favicon = iconElements[0].href;
}
}
if (!favicon.endsWith('.png') && dom.window.document.querySelector('meta[itemprop="image"]')) favicon = dom.window.document.querySelector('meta[itemprop="image"]').content;
if (favicon) {
if (favicon.startsWith('/')) favicon = (redirectUri || applink.upstreamUri) + favicon;
debug(`detectMetaInfo: found icon: ${favicon}`);
const [error, response] = await safe(superagent.get(favicon));
if (error) console.error(`Failed to fetch icon ${favicon}: `, error);
else if (response.ok && response.headers['content-type'] === 'image/png') applink.icon = response.body;
else console.error(`Failed to fetch icon ${favicon}: statusCode=${response.status}`);
} else {
console.error(`Unable to find a suitable icon for ${applink.upstreamUri}`);
}
}
if (!applink.label) {
if (dom.window.document.querySelector('meta[property="og:title"]')) applink.label = dom.window.document.querySelector('meta[property="og:title"]').content;
else if (dom.window.document.querySelector('meta[property="og:site_name"]')) applink.label = dom.window.document.querySelector('meta[property="og:site_name"]').content;
else if (dom.window.document.title) applink.label = dom.window.document.title;
}
}
async function add(applink) {
assert.strictEqual(typeof applink, 'object');
assert.strictEqual(typeof applink.upstreamUri, 'string');
debug(`add: ${applink.upstreamUri}`, applink);
let error = validateUpstreamUri(applink.upstreamUri);
if (error) throw error;
if (applink.icon) {
if (!validator.isBase64(applink.icon)) throw new BoxError(BoxError.BAD_FIELD, 'icon is not base64');
applink.icon = Buffer.from(applink.icon, 'base64');
}
await detectMetaInfo(applink);
const data = {
id: uuid.v4(),
accessRestrictionJson: applink.accessRestriction ? JSON.stringify(applink.accessRestriction) : null,
label: applink.label || '',
tagsJson: applink.tags ? JSON.stringify(applink.tags) : null,
icon: applink.icon || null,
upstreamUri: applink.upstreamUri
};
const query = 'INSERT INTO applinks (id, accessRestrictionJson, label, tagsJson, icon, upstreamUri) VALUES (?, ?, ?, ?, ?, ?)';
const args = [ data.id, data.accessRestrictionJson, data.label, data.tagsJson, data.icon, data.upstreamUri ];
[error] = await safe(database.query(query, args));
if (error) throw error;
return data.id;
}
async function get(applinkId) {
assert.strictEqual(typeof applinkId, 'string');
const result = await database.query(`SELECT ${APPLINKS_FIELDS} FROM applinks WHERE id = ?`, [ applinkId ]);
if (result.length === 0) return null;
postProcess(result[0]);
return result[0];
}
async function update(applinkId, applink) {
assert.strictEqual(typeof applinkId, 'string');
assert.strictEqual(typeof applink, 'object');
assert.strictEqual(typeof applink.upstreamUri, 'string');
debug(`update: ${applink.upstreamUri}`, applink);
let error = validateUpstreamUri(applink.upstreamUri);
if (error) throw error;
if (applink.icon) {
if (!validator.isBase64(applink.icon)) throw new BoxError(BoxError.BAD_FIELD, 'icon is not base64');
applink.icon = Buffer.from(applink.icon, 'base64');
}
await detectMetaInfo(applink);
const query = 'UPDATE applinks SET label=?, icon=?, upstreamUri=?, tagsJson=?, accessRestrictionJson=? WHERE id = ?';
const args = [ applink.label, applink.icon || null, applink.upstreamUri, applink.tags ? JSON.stringify(applink.tags) : null, applink.accessRestriction ? JSON.stringify(applink.accessRestriction) : null, applinkId ];
const result = await database.query(query, args);
if (result.affectedRows !== 1) throw new BoxError(BoxError.NOT_FOUND, 'Applink not found');
}
async function remove(applinkId) {
assert.strictEqual(typeof applinkId, 'string');
const result = await database.query('DELETE FROM applinks WHERE id = ?', [ applinkId ]);
if (result.affectedRows !== 1) throw new BoxError(BoxError.NOT_FOUND, 'Applink not found');
}
async function getIcon(applinkId) {
assert.strictEqual(typeof applinkId, 'string');
const applink = await get(applinkId);
if (!applink) throw new BoxError(BoxError.NOT_FOUND, 'Applink not found');
return applink.icon;
}
+127 -52
View File
@@ -27,6 +27,7 @@ exports = module.exports = {
setAccessRestriction,
setOperators,
setCrontab,
setUpstreamUri,
setLabel,
setIcon,
setTags,
@@ -60,6 +61,8 @@ exports = module.exports = {
getLogPaths,
getLogs,
appendLogLine,
getCertificate,
start,
@@ -159,6 +162,7 @@ const appstore = require('./appstore.js'),
mail = require('./mail.js'),
manifestFormat = require('cloudron-manifestformat'),
mounts = require('./mounts.js'),
notifications = require('./notifications.js'),
once = require('./once.js'),
os = require('os'),
path = require('path'),
@@ -186,7 +190,7 @@ const APPS_FIELDS_PREFIXED = [ 'apps.id', 'apps.appStoreId', 'apps.installationS
'apps.health', 'apps.containerId', 'apps.manifestJson', 'apps.accessRestrictionJson', 'apps.memoryLimit', 'apps.cpuShares',
'apps.label', 'apps.tagsJson', 'apps.taskId', 'apps.reverseProxyConfigJson', 'apps.servicesConfigJson', 'apps.operatorsJson',
'apps.sso', 'apps.debugModeJson', 'apps.enableBackup', 'apps.proxyAuth', 'apps.containerIp', 'apps.crontab',
'apps.creationTime', 'apps.updateTime', 'apps.enableAutomaticUpdate',
'apps.creationTime', 'apps.updateTime', 'apps.enableAutomaticUpdate', 'apps.upstreamUri',
'apps.enableMailbox', 'apps.mailboxDisplayName', 'apps.mailboxName', 'apps.mailboxDomain', 'apps.enableInbox', 'apps.inboxName', 'apps.inboxDomain',
'apps.storageVolumeId', 'apps.storageVolumePrefix', 'apps.ts', 'apps.healthTime', '(apps.icon IS NOT NULL) AS hasIcon', '(apps.appStoreIcon IS NOT NULL) AS hasAppStoreIcon' ].join(',');
@@ -214,7 +218,6 @@ function validatePortBindings(portBindings, manifest) {
993, /* imaps */
995, /* pop3s */
2003, /* graphite (lo) */
2004, /* graphite (lo) */
2514, /* cloudron-syslog (lo) */
constants.PORT, /* app server (lo) */
constants.AUTHWALL_PORT, /* protected sites */
@@ -225,7 +228,6 @@ function validatePortBindings(portBindings, manifest) {
4190, /* managesieve */
5349, /* turn,stun TLS */
8000, /* ESXi monitoring */
8417, /* graphite (lo) */
];
const RESERVED_PORT_RANGES = [
@@ -239,7 +241,10 @@ function validatePortBindings(portBindings, manifest) {
if (!portBindings) return null;
for (let portName in portBindings) {
const tcpPorts = manifest.tcpPorts || { };
const udpPorts = manifest.udpPorts || { };
for (const portName in portBindings) {
if (!/^[a-zA-Z0-9_]+$/.test(portName)) return new BoxError(BoxError.BAD_FIELD, `${portName} is not a valid environment variable in portBindings`);
const hostPort = portBindings[portName];
@@ -247,14 +252,11 @@ function validatePortBindings(portBindings, manifest) {
if (RESERVED_PORTS.indexOf(hostPort) !== -1) return new BoxError(BoxError.BAD_FIELD, `Port ${hostPort} for ${portName} is reserved in portBindings`);
if (RESERVED_PORT_RANGES.find(range => (hostPort >= range[0] && hostPort <= range[1]))) return new BoxError(BoxError.BAD_FIELD, `Port ${hostPort} for ${portName} is reserved in portBindings`);
if (ALLOWED_PORTS.indexOf(hostPort) === -1 && (hostPort <= 1023 || hostPort > 65535)) return new BoxError(BoxError.BAD_FIELD, `${hostPort} for ${portName} is not in permitted range in portBindings`);
}
// it is OK if there is no 1-1 mapping between values in manifest.tcpPorts and portBindings. missing values implies
// that the user wants the service disabled
const tcpPorts = manifest.tcpPorts || { };
const udpPorts = manifest.udpPorts || { };
for (let portName in portBindings) {
if (!(portName in tcpPorts) && !(portName in udpPorts)) return new BoxError(BoxError.BAD_FIELD, `Invalid portBindings ${portName}`);
// it is OK if there is no 1-1 mapping between values in manifest.tcpPorts and portBindings. missing values implies the service is disabled
const portSpec = tcpPorts[portName] || udpPorts[portName];
if (!portSpec) return new BoxError(BoxError.BAD_FIELD, `Invalid portBinding ${portName}`);
if (portSpec.readOnly && portSpec.defaultValue !== hostPort) return new BoxError(BoxError.BAD_FIELD, `portBinding ${portName} is readOnly and cannot have a different value that the default`);
}
return null;
@@ -454,6 +456,23 @@ function validateBackupFormat(format) {
return new BoxError(BoxError.BAD_FIELD, 'Invalid backup format');
}
function validateUpstreamUri(upstreamUri) {
assert.strictEqual(typeof upstreamUri, 'string');
if (!upstreamUri) return null;
const uri = safe(() => new URL(upstreamUri));
if (!uri) return new BoxError(BoxError.BAD_FIELD, `upstreamUri is invalid: ${safe.error.message}`);
if (uri.protocol !== 'http:' && uri.protocol !== 'https:') return new BoxError(BoxError.BAD_FIELD, 'upstreamUri has an unsupported scheme');
if (uri.search || uri.hash) return new BoxError(BoxError.BAD_FIELD, 'upstreamUri cannot have search or hash');
if (uri.pathname !== '/') return new BoxError(BoxError.BAD_FIELD, 'upstreamUri cannot have a path');
// we use the uri in a named location @wellknown-upstream. nginx does not support having paths in it
if (upstreamUri.endsWith('/')) return new BoxError(BoxError.BAD_FIELD, 'upstreamUri cannot have a path');
return null;
}
function validateLabel(label) {
if (label === null) return null;
@@ -551,21 +570,36 @@ async function getStorageDir(app) {
return path.join(volume.hostPath, app.storageVolumePrefix);
}
function removeCertificateKeys(app) {
if (app.certificate) delete app.certificate.key;
app.secondaryDomains.forEach(sd => { if (sd.certificate) delete sd.certificate.key; });
app.aliasDomains.forEach(ad => { if (ad.certificate) delete ad.certificate.key; });
app.redirectDomains.forEach(rd => { if (rd.certificate) delete rd.certificate.key; });
}
function removeInternalFields(app) {
return _.pick(app,
const result = _.pick(app,
'id', 'appStoreId', 'installationState', 'error', 'runState', 'health', 'taskId',
'subdomain', 'domain', 'fqdn', 'crontab',
'subdomain', 'domain', 'fqdn', 'certificate', 'crontab', 'upstreamUri',
'accessRestriction', 'manifest', 'portBindings', 'iconUrl', 'memoryLimit', 'cpuShares', 'operators',
'sso', 'debugMode', 'reverseProxyConfig', 'enableBackup', 'creationTime', 'updateTime', 'ts', 'tags',
'label', 'secondaryDomains', 'redirectDomains', 'aliasDomains', 'env', 'enableAutomaticUpdate', 'storageVolumeId', 'storageVolumePrefix', 'mounts',
'label', 'secondaryDomains', 'redirectDomains', 'aliasDomains', 'env', 'enableAutomaticUpdate',
'storageVolumeId', 'storageVolumePrefix', 'mounts',
'enableMailbox', 'mailboxDisplayName', 'mailboxName', 'mailboxDomain', 'enableInbox', 'inboxName', 'inboxDomain');
removeCertificateKeys(result);
return result;
}
// non-admins can only see these
function removeRestrictedFields(app) {
return _.pick(app,
'id', 'appStoreId', 'installationState', 'error', 'runState', 'health', 'taskId', 'accessRestriction', 'secondaryDomains', 'redirectDomains', 'aliasDomains', 'sso',
'subdomain', 'domain', 'fqdn', 'manifest', 'portBindings', 'iconUrl', 'creationTime', 'ts', 'tags', 'label', 'enableBackup');
const result = _.pick(app,
'id', 'appStoreId', 'installationState', 'error', 'runState', 'health', 'taskId', 'accessRestriction',
'secondaryDomains', 'redirectDomains', 'aliasDomains', 'sso', 'subdomain', 'domain', 'fqdn', 'certificate',
'manifest', 'portBindings', 'iconUrl', 'creationTime', 'ts', 'tags', 'label', 'enableBackup', 'upstreamUri');
removeCertificateKeys(result);
return result;
}
async function getIcon(app, options) {
@@ -663,30 +697,35 @@ function postProcess(result) {
const subdomains = JSON.parse(result.subdomains),
domains = JSON.parse(result.domains),
subdomainTypes = JSON.parse(result.subdomainTypes),
subdomainEnvironmentVariables = JSON.parse(result.subdomainEnvironmentVariables);
subdomainEnvironmentVariables = JSON.parse(result.subdomainEnvironmentVariables),
subdomainCertificateJsons = JSON.parse(result.subdomainCertificateJsons);
delete result.subdomains;
delete result.domains;
delete result.subdomainTypes;
delete result.subdomainEnvironmentVariables;
delete result.subdomainCertificateJsons;
result.secondaryDomains = [];
result.redirectDomains = [];
result.aliasDomains = [];
for (let i = 0; i < subdomainTypes.length; i++) {
const subdomain = subdomains[i], domain = domains[i], certificate = safe.JSON.parse(subdomainCertificateJsons[i]);
if (subdomainTypes[i] === exports.LOCATION_TYPE_PRIMARY) {
result.subdomain = subdomains[i];
result.domain = domains[i];
result.subdomain = subdomain;
result.domain = domain;
result.certificate = certificate;
} else if (subdomainTypes[i] === exports.LOCATION_TYPE_SECONDARY) {
result.secondaryDomains.push({ domain: domains[i], subdomain: subdomains[i], environmentVariable: subdomainEnvironmentVariables[i] });
result.secondaryDomains.push({ domain, subdomain, certificate, environmentVariable: subdomainEnvironmentVariables[i] });
} else if (subdomainTypes[i] === exports.LOCATION_TYPE_REDIRECT) {
result.redirectDomains.push({ domain: domains[i], subdomain: subdomains[i] });
result.redirectDomains.push({ domain, subdomain, certificate });
} else if (subdomainTypes[i] === exports.LOCATION_TYPE_ALIAS) {
result.aliasDomains.push({ domain: domains[i], subdomain: subdomains[i] });
result.aliasDomains.push({ domain, subdomain, certificate });
}
}
let envNames = JSON.parse(result.envNames), envValues = JSON.parse(result.envValues);
const envNames = JSON.parse(result.envNames), envValues = JSON.parse(result.envValues);
delete result.envNames;
delete result.envValues;
result.env = {};
@@ -694,7 +733,7 @@ function postProcess(result) {
if (envNames[i]) result.env[envNames[i]] = envValues[i];
}
let volumeIds = JSON.parse(result.volumeIds);
const volumeIds = JSON.parse(result.volumeIds);
delete result.volumeIds;
let volumeReadOnlys = JSON.parse(result.volumeReadOnlys);
delete result.volumeReadOnlys;
@@ -730,7 +769,7 @@ function isAdmin(user) {
}
function isOperator(app, user) {
assert.strictEqual(typeof app, 'object');
assert.strictEqual(typeof app, 'object'); // IMPORTANT: can also be applink
assert.strictEqual(typeof user, 'object');
if (!app.operators) return isAdmin(user);
@@ -743,7 +782,7 @@ function isOperator(app, user) {
}
function canAccess(app, user) {
assert.strictEqual(typeof app, 'object');
assert.strictEqual(typeof app, 'object'); // IMPORTANT: can also be applink
assert.strictEqual(typeof user, 'object');
if (app.accessRestriction === null) return true;
@@ -791,6 +830,7 @@ async function add(id, appStoreId, manifest, subdomain, domain, portBindings, da
reverseProxyConfigJson = data.reverseProxyConfig ? JSON.stringify(data.reverseProxyConfig) : null,
servicesConfigJson = data.servicesConfig ? JSON.stringify(data.servicesConfig) : null,
enableMailbox = data.enableMailbox || false,
upstreamUri = data.upstreamUri || '',
icon = data.icon || null;
const queries = [];
@@ -798,11 +838,11 @@ async function add(id, appStoreId, manifest, subdomain, domain, portBindings, da
queries.push({
query: 'INSERT INTO apps (id, appStoreId, manifestJson, installationState, runState, accessRestrictionJson, memoryLimit, cpuShares, '
+ 'sso, debugModeJson, mailboxName, mailboxDomain, label, tagsJson, reverseProxyConfigJson, servicesConfigJson, icon, '
+ 'enableMailbox, mailboxDisplayName) '
+ ' VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
+ 'enableMailbox, mailboxDisplayName, upstreamUri) '
+ ' VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
args: [ id, appStoreId, manifestJson, installationState, runState, accessRestrictionJson, memoryLimit, cpuShares,
sso, debugModeJson, mailboxName, mailboxDomain, label, tagsJson, reverseProxyConfigJson, servicesConfigJson, icon,
enableMailbox, mailboxDisplayName ]
enableMailbox, mailboxDisplayName, upstreamUri ]
});
queries.push({
@@ -1025,9 +1065,9 @@ async function getDomainObjectMap() {
// each query simply join apps table with another table by id. we then join the full result together
const PB_QUERY = 'SELECT id, GROUP_CONCAT(CAST(appPortBindings.hostPort AS CHAR(6))) AS hostPorts, GROUP_CONCAT(appPortBindings.environmentVariable) AS environmentVariables, GROUP_CONCAT(appPortBindings.type) AS portTypes FROM apps LEFT JOIN appPortBindings ON apps.id = appPortBindings.appId GROUP BY apps.id';
const ENV_QUERY = 'SELECT id, JSON_ARRAYAGG(appEnvVars.name) AS envNames, JSON_ARRAYAGG(appEnvVars.value) AS envValues FROM apps LEFT JOIN appEnvVars ON apps.id = appEnvVars.appId GROUP BY apps.id';
const SUBDOMAIN_QUERY = 'SELECT id, JSON_ARRAYAGG(locations.subdomain) AS subdomains, JSON_ARRAYAGG(locations.domain) AS domains, JSON_ARRAYAGG(locations.type) AS subdomainTypes, JSON_ARRAYAGG(locations.environmentVariable) AS subdomainEnvironmentVariables FROM apps LEFT JOIN locations ON apps.id = locations.appId GROUP BY apps.id';
const SUBDOMAIN_QUERY = 'SELECT id, JSON_ARRAYAGG(locations.subdomain) AS subdomains, JSON_ARRAYAGG(locations.domain) AS domains, JSON_ARRAYAGG(locations.type) AS subdomainTypes, JSON_ARRAYAGG(locations.environmentVariable) AS subdomainEnvironmentVariables, JSON_ARRAYAGG(locations.certificateJson) AS subdomainCertificateJsons FROM apps LEFT JOIN locations ON apps.id = locations.appId GROUP BY apps.id';
const MOUNTS_QUERY = 'SELECT id, JSON_ARRAYAGG(appMounts.volumeId) AS volumeIds, JSON_ARRAYAGG(appMounts.readOnly) AS volumeReadOnlys FROM apps LEFT JOIN appMounts ON apps.id = appMounts.appId GROUP BY apps.id';
const APPS_QUERY = `SELECT ${APPS_FIELDS_PREFIXED}, hostPorts, environmentVariables, portTypes, envNames, envValues, subdomains, domains, subdomainTypes, subdomainEnvironmentVariables, volumeIds, volumeReadOnlys FROM apps`
const APPS_QUERY = `SELECT ${APPS_FIELDS_PREFIXED}, hostPorts, environmentVariables, portTypes, envNames, envValues, subdomains, domains, subdomainTypes, subdomainEnvironmentVariables, subdomainCertificateJsons, volumeIds, volumeReadOnlys FROM apps`
+ ` LEFT JOIN (${PB_QUERY}) AS q1 on q1.id = apps.id`
+ ` LEFT JOIN (${ENV_QUERY}) AS q2 on q2.id = apps.id`
+ ` LEFT JOIN (${SUBDOMAIN_QUERY}) AS q3 on q3.id = apps.id`
@@ -1283,6 +1323,7 @@ async function install(data, auditSource) {
overwriteDns = 'overwriteDns' in data ? data.overwriteDns : false,
skipDnsSetup = 'skipDnsSetup' in data ? data.skipDnsSetup : false,
appStoreId = data.appStoreId,
upstreamUri = data.upstreamUri || '',
manifest = data.manifest;
let error = manifestFormat.parse(manifest);
@@ -1306,6 +1347,9 @@ async function install(data, auditSource) {
error = validateLabel(label);
if (error) throw error;
error = validateUpstreamUri(upstreamUri);
if (error) throw error;
error = validateTags(tags);
if (error) throw error;
@@ -1363,6 +1407,7 @@ async function install(data, auditSource) {
tags,
icon,
enableMailbox,
upstreamUri,
runState: exports.RSTATE_RUNNING,
installationState: exports.ISTATE_PENDING_INSTALL
};
@@ -1430,6 +1475,22 @@ async function setCrontab(app, crontab, auditSource) {
await eventlog.add(eventlog.ACTION_APP_CONFIGURE, auditSource, { appId, app, crontab });
}
async function setUpstreamUri(app, upstreamUri, auditSource) {
assert.strictEqual(typeof app, 'object');
assert.strictEqual(typeof upstreamUri, 'string');
assert.strictEqual(typeof auditSource, 'object');
const appId = app.id;
const error = validateUpstreamUri(upstreamUri);
if (error) throw error;
await reverseProxy.writeAppConfigs(_.extend({}, app, { upstreamUri }));
await update(appId, { upstreamUri });
await eventlog.add(eventlog.ACTION_APP_CONFIGURE, auditSource, { appId, app, upstreamUri });
}
async function setLabel(app, label, auditSource) {
assert.strictEqual(typeof app, 'object');
assert.strictEqual(typeof label, 'string');
@@ -1703,7 +1764,7 @@ async function setReverseProxyConfig(app, reverseProxyConfig, auditSource) {
error = validateRobotsTxt(reverseProxyConfig.robotsTxt);
if (error) throw error;
await reverseProxy.writeAppConfig(_.extend({}, app, { reverseProxyConfig }));
await reverseProxy.writeAppConfigs(_.extend({}, app, { reverseProxyConfig }));
await update(appId, { reverseProxyConfig });
@@ -1715,18 +1776,23 @@ async function setCertificate(app, data, auditSource) {
assert(data && typeof data === 'object');
assert.strictEqual(typeof auditSource, 'object');
const appId = app.id;
const { location, domain, cert, key } = data;
const { subdomain, domain, cert, key } = data;
const domainObject = await domains.get(domain);
if (domainObject === null) throw new BoxError(BoxError.NOT_FOUND, 'Domain not found');
if (cert && key) {
const error = reverseProxy.validateCertificate(location, domainObject, { cert, key });
const error = reverseProxy.validateCertificate(subdomain, domainObject, { cert, key });
if (error) throw error;
}
await reverseProxy.setAppCertificate(location, domainObject, { cert, key });
await eventlog.add(eventlog.ACTION_APP_CONFIGURE, auditSource, { appId, app, cert, key });
const certificate = cert && key ? { cert, key } : null;
const result = await database.query('UPDATE locations SET certificateJson=? WHERE location=? AND domain=?', [ certificate ? JSON.stringify(certificate) : null, subdomain, domain ]);
if (result.affectedRows === 0) throw new BoxError(BoxError.NOT_FOUND, 'Location not found');
app = await get(app.id); // refresh app object
await reverseProxy.setUserCertificate(app, dns.fqdn(subdomain, domainObject), certificate);
await eventlog.add(eventlog.ACTION_APP_CONFIGURE, auditSource, { appId: app.id, app, subdomain, domain, cert });
}
async function setLocation(app, data, auditSource) {
@@ -1982,13 +2048,23 @@ async function getLogs(app, options) {
return transformStream;
}
// never fails just prints error
async function appendLogLine(app, line) {
assert.strictEqual(typeof app, 'object');
assert.strictEqual(typeof line, 'string');
const logFilePath = path.join(paths.LOG_DIR, app.id, 'app.log');
if (!safe.fs.appendFileSync(logFilePath, line)) console.error(`Could not append log line for app ${app.id} at ${logFilePath}: ${safe.error.message}`);
}
async function getCertificate(subdomain, domain) {
assert.strictEqual(typeof subdomain, 'string');
assert.strictEqual(typeof domain, 'string');
const result = await database.query('SELECT certificateJson FROM locations WHERE subdomain=? AND domain=?', [ subdomain, domain ]);
if (result.length === 0) return null;
return JSON.parse(result[0].certificateJson);
return safe.JSON.parse(result[0].certificateJson);
}
// does a re-configure when called from most states. for install/clone errors, it re-installs with an optional manifest
@@ -2096,20 +2172,18 @@ async function importApp(app, data, auditSource) {
const appId = app.id;
// all fields are optional
data.remotePath = data.remotePath || null;
data.backupFormat = data.backupFormat || null;
data.backupConfig = data.backupConfig || null;
const { remotePath, backupFormat, backupConfig } = data;
let error = backupFormat ? validateBackupFormat(backupFormat) : null;
let error = checkAppState(app, exports.ISTATE_PENDING_IMPORT);
if (error) throw error;
error = checkAppState(app, exports.ISTATE_PENDING_IMPORT);
if (error) throw error;
let restoreConfig;
// TODO: make this smarter to do a read-only test and check if the file exists in the storage backend
if (backupConfig) {
if (data.remotePath) { // if not provided, we import in-place
error = validateBackupFormat(backupFormat);
if (error) throw error;
// TODO: make this smarter to do a read-only test and check if the file exists in the storage backend
if (mounts.isManagedProvider(backupConfig.provider)) {
error = mounts.validateMountOptions(backupConfig.provider, backupConfig.mountOptions);
if (error) throw error;
@@ -2125,18 +2199,18 @@ async function importApp(app, data, auditSource) {
}
error = await backups.testProviderConfig(backupConfig);
if (error) throw error;
}
if (backupConfig) {
if ('password' in backupConfig) {
backupConfig.encryption = backups.generateEncryptionKeysSync(backupConfig.password);
delete backupConfig.password;
} else {
backupConfig.encryption = null;
}
}
const restoreConfig = { remotePath, backupFormat, backupConfig };
restoreConfig = { remotePath, backupFormat, backupConfig };
} else {
restoreConfig = { remotePath: null };
}
const task = {
args: {
@@ -2490,6 +2564,7 @@ async function autoupdateApps(updateInfo, auditSource) { // updateInfo is { appI
if (!canAutoupdateApp(app, updateInfo[appId])) {
debug(`app ${app.fqdn} requires manual update`);
notifications.alert(notifications.ALERT_MANUAL_APP_UPDATE, `${app.manifest.title} at ${app.fqdn} requires manual update to version ${updateInfo[appId].manifest.version}`, `Changelog:\n${updateInfo[appId].manifest.changelog}\n`);
continue;
}
+26 -32
View File
@@ -17,7 +17,6 @@ const apps = require('./apps.js'),
AuditSource = require('./auditsource.js'),
backuptask = require('./backuptask.js'),
BoxError = require('./boxerror.js'),
collectd = require('./collectd.js'),
constants = require('./constants.js'),
debug = require('debug')('box:apptask'),
df = require('@sindresorhus/df'),
@@ -45,12 +44,8 @@ const MV_VOLUME_CMD = path.join(__dirname, 'scripts/mvvolume.sh'),
LOGROTATE_CONFIG_EJS = fs.readFileSync(__dirname + '/logrotate.ejs', { encoding: 'utf8' }),
CONFIGURE_LOGROTATE_CMD = path.join(__dirname, 'scripts/configurelogrotate.sh');
// https://rootlesscontaine.rs/getting-started/common/cgroup2/#checking-whether-cgroup-v2-is-already-enabled
const CGROUP_VERSION = fs.existsSync('/sys/fs/cgroup/cgroup.controllers') ? '2' : '1';
const COLLECTD_CONFIG_EJS = fs.readFileSync(`${__dirname}/collectd/app_cgroup_v${CGROUP_VERSION}.ejs`, { encoding: 'utf8' });
function makeTaskError(error, app) {
assert.strictEqual(typeof error, 'object');
assert(error instanceof BoxError);
assert.strictEqual(typeof app, 'object');
// track a few variables which helps 'repair' restart the task (see also scheduleTask in apps.js)
@@ -74,6 +69,8 @@ async function updateApp(app, values) {
async function allocateContainerIp(app) {
assert.strictEqual(typeof app, 'object');
if (app.manifest.id === constants.PROXY_APP_APPSTORE_ID) return;
await promiseRetry({ times: 10, interval: 0, debug }, async function () {
const iprange = iputils.intFromIp('172.18.20.255') - iputils.intFromIp('172.18.16.1');
let rnd = Math.floor(Math.random() * iprange);
@@ -86,6 +83,8 @@ async function createContainer(app) {
assert.strictEqual(typeof app, 'object');
assert(!app.containerId); // otherwise, it will trigger volumeFrom
if (app.manifest.id === constants.PROXY_APP_APPSTORE_ID) return;
debug('createContainer: creating container');
const container = await docker.createContainer(app);
@@ -94,7 +93,6 @@ async function createContainer(app) {
// re-generate configs that rely on container id
await addLogrotateConfig(app);
await addCollectdProfile(app);
}
async function deleteContainers(app, options) {
@@ -104,7 +102,6 @@ async function deleteContainers(app, options) {
debug('deleteContainer: deleting app containers (app, scheduler)');
// remove configs that rely on container id
await removeCollectdProfile(app);
await removeLogrotateConfig(app);
await docker.stopContainers(app.id);
await docker.deleteContainers(app.id, options);
@@ -157,20 +154,6 @@ async function deleteAppDir(app, options) {
}
}
async function addCollectdProfile(app) {
assert.strictEqual(typeof app, 'object');
const appDataDir = await apps.getStorageDir(app);
const collectdConf = ejs.render(COLLECTD_CONFIG_EJS, { appId: app.id, containerId: app.containerId, appDataDir });
await collectd.addProfile(app.id, collectdConf);
}
async function removeCollectdProfile(app) {
assert.strictEqual(typeof app, 'object');
await collectd.removeProfile(app.id);
}
async function addLogrotateConfig(app) {
assert.strictEqual(typeof app, 'object');
@@ -290,6 +273,9 @@ async function moveDataDir(app, targetVolumeId, targetVolumePrefix) {
async function downloadImage(manifest) {
assert.strictEqual(typeof manifest, 'object');
// skip for relay app
if (manifest.id === constants.PROXY_APP_APPSTORE_ID) return;
const info = await docker.info();
const [dfError, diskUsage] = await safe(df.file(info.DockerRootDir));
if (dfError) throw new BoxError(BoxError.FS_ERROR, `Error getting file system info: ${dfError.message}`);
@@ -304,6 +290,9 @@ async function startApp(app) {
if (app.runState === apps.RSTATE_STOPPED) return;
// skip for relay app
if (app.manifest.id === constants.PROXY_APP_APPSTORE_ID) return;
await docker.startContainer(app.id);
}
@@ -675,11 +664,10 @@ async function start(app, args, progressCallback) {
await progressCallback({ percent: 10, message: 'Starting app services' });
await services.startAppServices(app);
await progressCallback({ percent: 35, message: 'Starting container' });
await docker.startContainer(app.id);
await progressCallback({ percent: 60, message: 'Adding collectd profile' });
await addCollectdProfile(app);
if (app.manifest.id !== constants.PROXY_APP_APPSTORE_ID) {
await progressCallback({ percent: 35, message: 'Starting container' });
await docker.startContainer(app.id);
}
// stopped apps do not renew certs. currently, we don't do DNS to not overwrite existing user settings
await progressCallback({ percent: 80, message: 'Configuring reverse proxy' });
@@ -701,9 +689,6 @@ async function stop(app, args, progressCallback) {
await progressCallback({ percent: 50, message: 'Stopping app services' });
await services.stopAppServices(app);
await progressCallback({ percent: 80, message: 'Removing collectd profile' });
await removeCollectdProfile(app);
await progressCallback({ percent: 100, message: 'Done' });
await updateApp(app, { installationState: apps.ISTATE_INSTALLED, error: null, health: null });
}
@@ -713,8 +698,17 @@ async function restart(app, args, progressCallback) {
assert.strictEqual(typeof args, 'object');
assert.strictEqual(typeof progressCallback, 'function');
await progressCallback({ percent: 20, message: 'Restarting container' });
await docker.restartContainer(app.id);
if (app.manifest.id !== constants.PROXY_APP_APPSTORE_ID) {
await progressCallback({ percent: 10, message: 'Starting app services' });
await services.startAppServices(app);
await progressCallback({ percent: 20, message: 'Restarting container' });
await docker.restartContainer(app.id);
}
// stopped apps do not renew certs. currently, we don't do DNS to not overwrite existing user settings
await progressCallback({ percent: 80, message: 'Configuring reverse proxy' });
await reverseProxy.configureApp(app, AuditSource.APPTASK);
await progressCallback({ percent: 100, message: 'Done' });
await updateApp(app, { installationState: apps.ISTATE_INSTALLED, error: null, health: null });
+4 -8
View File
@@ -15,7 +15,6 @@ const apps = require('./apps.js'),
constants = require('./constants.js'),
debug = require('debug')('box:backupcleaner'),
moment = require('moment'),
mounts = require('./mounts.js'),
path = require('path'),
paths = require('./paths.js'),
safe = require('safetydance'),
@@ -272,12 +271,9 @@ async function run(progressCallback) {
const backupConfig = await settings.getBackupConfig();
if (mounts.isManagedProvider(backupConfig.provider) || backupConfig.provider === 'mountpoint') {
const hostPath = mounts.isManagedProvider(backupConfig.provider) ? paths.MANAGED_BACKUP_MOUNT_DIR : backupConfig.mountPoint;
const status = await mounts.getStatus(backupConfig.provider, hostPath); // { state, message }
debug(`clean: mount point status is ${JSON.stringify(status)}`);
if (status.state !== 'active') throw new BoxError(BoxError.MOUNT_ERROR, `Backup endpoint is not mounted: ${status.message}`);
}
const status = await storage.api(backupConfig.provider).getBackupProviderStatus(backupConfig);
debug(`clean: mount point status is ${JSON.stringify(status)}`);
if (status.state !== 'active') throw new BoxError(BoxError.MOUNT_ERROR, `Backup endpoint is not mounted: ${status.message}`);
if (backupConfig.retentionPolicy.keepWithinSecs < 0) {
debug('cleanup: keeping all backups');
@@ -293,7 +289,7 @@ async function run(progressCallback) {
await progressCallback({ percent: 40, message: 'Cleaning app backups' });
const removedAppBackupPaths = await cleanupAppBackups(backupConfig, referencedBackupIds, progressCallback);
await progressCallback({ percent: 70, message: 'Cleaning missing backups' });
await progressCallback({ percent: 70, message: 'Checking storage backend and removing stale entries in database' });
const missingBackupPaths = await cleanupMissingBackups(backupConfig, progressCallback);
await progressCallback({ percent: 90, message: 'Cleaning snapshots' });
+3 -3
View File
@@ -27,7 +27,7 @@ function getBackupFilePath(backupConfig, remotePath) {
assert.strictEqual(typeof backupConfig, 'object');
assert.strictEqual(typeof remotePath, 'string');
const rootPath = storage.api(backupConfig.provider).getRootPath(backupConfig);
const rootPath = storage.api(backupConfig.provider).getBackupRootPath(backupConfig);
return path.join(rootPath, remotePath);
}
@@ -46,7 +46,7 @@ function sync(backupConfig, remotePath, dataLayout, progressCallback, callback)
syncer.sync(dataLayout, function processTask(task, iteratorCallback) {
debug('sync: processing task: %j', task);
// the empty task.path is special to signify the directory
const destPath = task.path && backupConfig.encryption ? hush.encryptFilePath(task.path, backupConfig.encryption) : task.path;
const destPath = task.path && backupConfig.encryptedFilenames ? hush.encryptFilePath(task.path, backupConfig.encryption) : task.path;
const backupFilePath = path.join(getBackupFilePath(backupConfig, remotePath), destPath);
if (task.operation === 'removedir') {
@@ -164,7 +164,7 @@ function downloadDir(backupConfig, backupFilePath, dataLayout, progressCallback,
function downloadFile(entry, done) {
let relativePath = path.relative(backupFilePath, entry.fullPath);
if (backupConfig.encryption) {
if (backupConfig.encryptedFilenames) {
const { error, result } = hush.decryptFilePath(relativePath, backupConfig.encryption);
if (error) return done(new BoxError(BoxError.CRYPTO_ERROR, 'Unable to decrypt file'));
relativePath = result;
+1 -1
View File
@@ -23,7 +23,7 @@ function getBackupFilePath(backupConfig, remotePath) {
assert.strictEqual(typeof backupConfig, 'object');
assert.strictEqual(typeof remotePath, 'string');
const rootPath = storage.api(backupConfig.provider).getRootPath(backupConfig);
const rootPath = storage.api(backupConfig.provider).getBackupRootPath(backupConfig);
const fileType = backupConfig.encryption ? '.tar.gz.enc' : '.tar.gz';
return path.join(rootPath, remotePath + fileType);
+4 -21
View File
@@ -18,8 +18,6 @@ exports = module.exports = {
injectPrivateFields,
removePrivateFields,
configureCollectd,
generateEncryptionKeysSync,
getSnapshotInfo,
@@ -44,15 +42,12 @@ exports = module.exports = {
const assert = require('assert'),
BoxError = require('./boxerror.js'),
collectd = require('./collectd.js'),
constants = require('./constants.js'),
CronJob = require('cron').CronJob,
crypto = require('crypto'),
database = require('./database.js'),
debug = require('debug')('box:backups'),
ejs = require('ejs'),
eventlog = require('./eventlog.js'),
fs = require('fs'),
hat = require('./hat.js'),
locker = require('./locker.js'),
path = require('path'),
@@ -62,8 +57,6 @@ const assert = require('assert'),
storage = require('./storage.js'),
tasks = require('./tasks.js');
const COLLECTD_CONFIG_EJS = fs.readFileSync(__dirname + '/collectd/cloudron-backup.ejs', { encoding: 'utf8' });
const BACKUPS_FIELDS = [ 'id', 'remotePath', 'label', 'identifier', 'creationTime', 'packageVersion', 'type', 'dependsOnJson', 'state', 'manifestJson', 'format', 'preserveSecs', 'encryptionVersion' ];
function postProcess(result) {
@@ -127,7 +120,8 @@ async function add(data) {
const creationTime = data.creationTime || new Date(); // allow tests to set the time
const manifestJson = JSON.stringify(data.manifest);
const id = `${data.type}_${data.identifier}_v${data.packageVersion}_${hat(256)}`; // id is used by the UI to derive dependent packages. making this a UUID will require a lot of db querying
const prefixId = data.type === exports.BACKUP_TYPE_APP ? `${data.type}_${data.identifier}` : data.type; // type and identifier are same for other types
const id = `${prefixId}_v${data.packageVersion}_${hat(256)}`; // id is used by the UI to derive dependent packages. making this a UUID will require a lot of db querying
const [error] = await safe(database.query('INSERT INTO backups (id, remotePath, identifier, encryptionVersion, packageVersion, type, creationTime, state, dependsOnJson, manifestJson, format, preserveSecs) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
[ id, data.remotePath, data.identifier, data.encryptionVersion, data.packageVersion, data.type, creationTime, data.state, JSON.stringify(data.dependsOn), manifestJson, data.format, data.preserveSecs ]));
@@ -176,7 +170,7 @@ function validateLabel(label) {
assert.strictEqual(typeof label, 'string');
if (label.length >= 200) return new BoxError(BoxError.BAD_FIELD, 'label too long');
if (/[^a-zA-Z0-9._()-]/.test(label)) return new BoxError(BoxError.BAD_FIELD, 'label can only contain alphanumerals, dot, hyphen, brackets or underscore');
if (/[^a-zA-Z0-9._() -]/.test(label)) return new BoxError(BoxError.BAD_FIELD, 'label can only contain alphanumerals, space, dot, hyphen, brackets or underscore');
return null;
}
@@ -241,7 +235,7 @@ async function startBackupTask(auditSource) {
const errorMessage = error ? error.message : '';
const timedOut = error ? error.code === tasks.ETIMEOUT : false;
const backup = await get(backupId);
const backup = backupId ? await get(backupId) : null;
await safe(eventlog.add(eventlog.ACTION_BACKUP_FINISH, auditSource, { taskId, errorMessage, timedOut, backupId, remotePath: backup?.remotePath }), { debug });
});
@@ -319,17 +313,6 @@ async function startCleanupTask(auditSource) {
return taskId;
}
async function configureCollectd(backupConfig) {
assert.strictEqual(typeof backupConfig, 'object');
if (backupConfig.provider === 'filesystem') {
const collectdConf = ejs.render(COLLECTD_CONFIG_EJS, { backupDir: backupConfig.backupFolder });
await collectd.addProfile('cloudron-backup', collectdConf);
} else {
await collectd.removeProfile('cloudron-backup');
}
}
async function testConfig(backupConfig) {
assert.strictEqual(typeof backupConfig, 'object');
+37 -1
View File
@@ -47,6 +47,41 @@ function canBackupApp(app) {
app.installationState === apps.ISTATE_PENDING_UPDATE; // called from apptask
}
// binary units (non SI) 1024 based
function prettyBytes(bytes) {
assert.strictEqual(typeof bytes, 'number');
const i = Math.floor(Math.log(bytes) / Math.log(1024)),
sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
return (bytes / Math.pow(1024, i)).toFixed(2) * 1 + '' + sizes[i];
}
async function checkPreconditions(backupConfig, dataLayout) {
assert.strictEqual(typeof backupConfig, 'object');
assert(dataLayout instanceof DataLayout, 'dataLayout must be a DataLayout');
// check mount status before uploading
const status = await storage.api(backupConfig.provider).getBackupProviderStatus(backupConfig);
debug(`upload: mount point status is ${JSON.stringify(status)}`);
if (status.state !== 'active') throw new BoxError(BoxError.MOUNT_ERROR, `Backup endpoint is not mounted: ${status.message}`);
// check availabe size. this requires root for df to work
const df = await storage.api(backupConfig.provider).getAvailableSize(backupConfig);
let used = 0;
for (const localPath of dataLayout.localPaths()) {
debug(`checkPreconditions: getting disk usage of ${localPath}`);
const result = safe.child_process.execSync(`du -Dsb ${localPath}`, { encoding: 'utf8' });
if (!result) throw new BoxError(BoxError.FS_ERROR, `du error: ${safe.error.message}`);
used += parseInt(result, 10);
}
debug(`checkPreconditions: ${used} bytes`);
const needed = 0.6 * used + (1024 * 1024 * 1024); // check if there is atleast 1GB left afterwards. aim for 60% because rsync/tgz won't need full 100%
if (df.available <= needed) throw new BoxError(BoxError.FS_ERROR, `Not enough disk space for backup. Needed: ${prettyBytes(needed)} Available: ${prettyBytes(df.available)}`);
}
// this function is called via backupupload (since it needs root to traverse app's directory)
async function upload(remotePath, format, dataLayoutString, progressCallback) {
assert.strictEqual(typeof remotePath, 'string');
@@ -58,7 +93,8 @@ async function upload(remotePath, format, dataLayoutString, progressCallback) {
const dataLayout = DataLayout.fromString(dataLayoutString);
const backupConfig = await settings.getBackupConfig();
await safe(storage.api(backupConfig.provider).checkPreconditions(backupConfig, dataLayout));
await checkPreconditions(backupConfig, dataLayout);
await backupFormat.api(format).upload(backupConfig, remotePath, dataLayout, progressCallback);
}
+12 -11
View File
@@ -19,6 +19,8 @@ exports = module.exports = {
renewCerts,
syncDnsRecords,
updateDiskUsage,
runSystemChecks
};
@@ -26,7 +28,6 @@ const apps = require('./apps.js'),
appstore = require('./appstore.js'),
assert = require('assert'),
AuditSource = require('./auditsource.js'),
backups = require('./backups.js'),
BoxError = require('./boxerror.js'),
branding = require('./branding.js'),
constants = require('./constants.js'),
@@ -108,12 +109,6 @@ async function runStartupTasks() {
// stop all the systemd tasks
tasks.push(platform.stopAllTasks);
// this configures collectd to collect backup storage metrics if filesystem is used. This is also triggerd when the settings change with the rest api
tasks.push(async function () {
const backupConfig = await settings.getBackupConfig();
await backups.configureCollectd(backupConfig);
});
// always generate webadmin config since we have no versioning mechanism for the ejs
tasks.push(async function () {
if (!settings.dashboardDomain()) return;
@@ -140,7 +135,7 @@ async function runStartupTasks() {
// we used to run tasks in parallel but simultaneous nginx reloads was causing issues
for (let i = 0; i < tasks.length; i++) {
const [error] = await safe(tasks[i]());
if (error) debug(`Startup task at index ${i} failed: ${error.message}`);
if (error) debug(`Startup task at index ${i} failed: ${error.message} ${error.stack}`);
}
}
@@ -267,12 +262,12 @@ async function prepareDashboardDomain(domain, auditSource) {
const domainObject = await domains.get(domain);
if (!domain) throw new BoxError(BoxError.NOT_FOUND, 'No such domain');
const fqdn = dns.fqdn(constants.DASHBOARD_LOCATION, domainObject);
const fqdn = dns.fqdn(constants.DASHBOARD_SUBDOMAIN, domainObject);
const result = await apps.list();
if (result.some(app => app.fqdn === fqdn)) throw new BoxError(BoxError.BAD_STATE, 'Dashboard location conflicts with an existing app');
const taskId = await tasks.add(tasks.TASK_SETUP_DNS_AND_CERT, [ constants.DASHBOARD_LOCATION, domain, auditSource ]);
const taskId = await tasks.add(tasks.TASK_SETUP_DNS_AND_CERT, [ constants.DASHBOARD_SUBDOMAIN, domain, auditSource ]);
tasks.startTask(taskId, {});
@@ -290,7 +285,7 @@ async function setDashboardDomain(domain, auditSource) {
if (!domain) throw new BoxError(BoxError.NOT_FOUND, 'No such domain');
await reverseProxy.writeDashboardConfig(domainObject);
const fqdn = dns.fqdn(constants.DASHBOARD_LOCATION, domainObject);
const fqdn = dns.fqdn(constants.DASHBOARD_SUBDOMAIN, domainObject);
await settings.setDashboardLocation(domain, fqdn);
@@ -351,3 +346,9 @@ async function syncDnsRecords(options) {
tasks.startTask(taskId, {});
return taskId;
}
async function updateDiskUsage() {
const taskId = await tasks.add(tasks.TASK_UPDATE_DISK_USAGE, []);
tasks.startTask(taskId, {});
return taskId;
}
-43
View File
@@ -1,43 +0,0 @@
'use strict';
exports = module.exports = {
addProfile,
removeProfile
};
const assert = require('assert'),
BoxError = require('./boxerror.js'),
debug = require('debug')('collectd'),
path = require('path'),
paths = require('./paths.js'),
safe = require('safetydance'),
shell = require('./shell.js');
const CONFIGURE_COLLECTD_CMD = path.join(__dirname, 'scripts/configurecollectd.sh');
async function addProfile(name, profile) {
assert.strictEqual(typeof name, 'string');
assert.strictEqual(typeof profile, 'string');
const configFilePath = path.join(paths.COLLECTD_APPCONFIG_DIR, `${name}.conf`);
// skip restarting collectd if the profile already exists with the same contents
const currentProfile = safe.fs.readFileSync(configFilePath, 'utf8') || '';
if (currentProfile === profile) return;
if (!safe.fs.writeFileSync(configFilePath, profile)) throw new BoxError(BoxError.FS_ERROR, `Error writing collectd config: ${safe.error.message}`);
const [error] = await safe(shell.promises.sudo('addCollectdProfile', [ CONFIGURE_COLLECTD_CMD, 'add', name ], {}));
if (error) throw new BoxError(BoxError.COLLECTD_ERROR, 'Could not add collectd config');
}
async function removeProfile(name) {
assert.strictEqual(typeof name, 'string');
if (!safe.fs.unlinkSync(path.join(paths.COLLECTD_APPCONFIG_DIR, `${name}.conf`))) {
if (safe.error.code !== 'ENOENT') debug('Error removing collectd profile', safe.error);
}
const [error] = await safe(shell.promises.sudo('removeCollectdProfile', [ CONFIGURE_COLLECTD_CMD, 'remove', name ], {}));
if (error) throw new BoxError(BoxError.COLLECTD_ERROR, 'Could not remove collectd config');
}
-42
View File
@@ -1,42 +0,0 @@
LoadPlugin "table"
<Plugin table>
<Table "/sys/fs/cgroup/memory/docker/<%= containerId %>/memory.stat">
Instance "<%= appId %>-memory"
Separator " \\n"
<Result>
Type gauge
InstancesFrom 0
ValuesFrom 1
</Result>
</Table>
<Table "/sys/fs/cgroup/memory/docker/<%= containerId %>/memory.max_usage_in_bytes">
Instance "<%= appId %>-memory"
Separator "\\n"
<Result>
Type gauge
InstancePrefix "max_usage_in_bytes"
ValuesFrom 0
</Result>
</Table>
<Table "/sys/fs/cgroup/cpuacct/docker/<%= containerId %>/cpuacct.stat">
Instance "<%= appId %>-cpu"
Separator " \\n"
<Result>
Type gauge
InstancesFrom 0
ValuesFrom 1
</Result>
</Table>
</Plugin>
<Plugin python>
<Module du>
<Path>
Instance "<%= appId %>"
Dir "<%= appDataDir %>"
</Path>
</Module>
</Plugin>
-42
View File
@@ -1,42 +0,0 @@
LoadPlugin "table"
<Plugin table>
<Table "/sys/fs/cgroup/docker/<%= containerId %>/memory.stat">
Instance "<%= appId %>-memory"
Separator " \\n"
<Result>
Type gauge
InstancesFrom 0
ValuesFrom 1
</Result>
</Table>
<Table "/sys/fs/cgroup/docker/<%= containerId %>/memory.max">
Instance "<%= appId %>-memory"
Separator "\\n"
<Result>
Type gauge
InstancePrefix "max_usage_in_bytes"
ValuesFrom 0
</Result>
</Table>
<Table "/sys/fs/cgroup/docker/<%= containerId %>/cpu.stat">
Instance "<%= appId %>-cpu"
Separator " \\n"
<Result>
Type gauge
InstancesFrom 0
ValuesFrom 1
</Result>
</Table>
</Plugin>
<Plugin python>
<Module du>
<Path>
Instance "<%= appId %>"
Dir "<%= appDataDir %>"
</Path>
</Module>
</Plugin>
+5 -3
View File
@@ -7,8 +7,8 @@ const CLOUDRON = process.env.BOX_ENV === 'cloudron',
TEST = process.env.BOX_ENV === 'test';
exports = module.exports = {
SMTP_LOCATION: 'smtp',
IMAP_LOCATION: 'imap',
SMTP_SUBDOMAIN: 'smtp',
IMAP_SUBDOMAIN: 'imap',
// These are combined into one array because users and groups become mailboxes
RESERVED_NAMES: [
@@ -22,7 +22,7 @@ exports = module.exports = {
'admins', 'users' // ldap code uses 'users' pseudo group
],
DASHBOARD_LOCATION: 'my',
DASHBOARD_SUBDOMAIN: 'my',
PORT: CLOUDRON ? 3000 : 5454,
INTERNAL_SMTP_PORT: 2525, // this value comes from the mail container
@@ -49,6 +49,8 @@ exports = module.exports = {
],
DEMO_APP_LIMIT: 20,
PROXY_APP_APPSTORE_ID: 'io.cloudron.builtin.appproxy',
AUTOUPDATE_PATTERN_NEVER: 'never',
// the db field is a blob so we make this explicit
+33 -12
View File
@@ -28,13 +28,13 @@ const appHealthMonitor = require('./apphealthmonitor.js'),
dyndns = require('./dyndns.js'),
eventlog = require('./eventlog.js'),
janitor = require('./janitor.js'),
paths = require('./paths.js'),
safe = require('safetydance'),
scheduler = require('./scheduler.js'),
settings = require('./settings.js'),
system = require('./system.js'),
updater = require('./updater.js'),
updateChecker = require('./updatechecker.js'),
userdirectory = require('./userdirectory.js'),
_ = require('underscore');
const gJobs = {
@@ -61,12 +61,36 @@ const gJobs = {
// Months: 0-11
// Day of Week: 0-6
async function startJobs() {
debug('startJobs: starting cron jobs');
function getCronSeed() {
let hour = null;
let minute = null;
const seedData = safe.fs.readFileSync(paths.CRON_SEED_FILE, 'utf8') || '';
const parts = seedData.split(':');
if (parts.length === 2) {
hour = parseInt(parts[0]) || null;
minute = parseInt(parts[1]) || null;
}
if ((hour == null || hour < 0 || hour > 23) || (minute == null || minute < 0 || minute > 60)) {
hour = Math.floor(24 * Math.random());
minute = Math.floor(60 * Math.random());
debug(`getCronSeed: writing new cron seed file with ${hour}:${minute} to ${paths.CRON_SEED_FILE}`);
safe.fs.writeFileSync(paths.CRON_SEED_FILE, `${hour}:${minute}`);
}
return { hour, minute };
}
async function startJobs() {
const { hour, minute } = getCronSeed();
debug(`startJobs: starting cron jobs with hour ${hour} and minute ${minute}`);
const randomTick = Math.floor(60*Math.random());
gJobs.systemChecks = new CronJob({
cronTime: `${randomTick} ${randomTick} 2 * * *`, // once a day. if you change this interval, change the notification messages with correct duration
cronTime: `00 ${minute} 2 * * *`, // once a day. if you change this interval, change the notification messages with correct duration
onTick: async () => await safe(cloudron.runSystemChecks(), { debug }),
start: true
});
@@ -79,7 +103,7 @@ async function startJobs() {
// this is run separately from the update itself so that the user can disable automatic updates but can still get a notification
gJobs.updateCheckerJob = new CronJob({
cronTime: `${randomTick} ${randomTick} 1,5,9,13,17,21,23 * * *`,
cronTime: `00 ${minute} 1,5,9,13,17,21,23 * * *`,
onTick: async () => await safe(updateChecker.checkForUpdates({ automatic: true }), { debug }),
start: true
});
@@ -98,7 +122,7 @@ async function startJobs() {
gJobs.cleanupEventlog = new CronJob({
cronTime: '00 */30 * * * *', // every 30 minutes
onTick: async () => await safe(eventlog.cleanup({ creationTime: new Date(Date.now() - 60 * 60 * 24 * 10 * 1000) }), { debug }), // 10 days ago
onTick: async () => await safe(eventlog.cleanup({ creationTime: new Date(Date.now() - 60 * 60 * 24 * 60 * 1000) }), { debug }), // 60 days ago
start: true
});
@@ -114,8 +138,9 @@ async function startJobs() {
start: true
});
// randomized per Cloudron based on hourlySeed
gJobs.certificateRenew = new CronJob({
cronTime: '00 00 */12 * * *', // every 12 hours
cronTime: `00 10 ${hour} * * *`,
onTick: async () => await safe(cloudron.renewCerts({}, AuditSource.CRON), { debug }),
start: true
});
@@ -148,10 +173,6 @@ async function handleSettingsChanged(key, value) {
await stopJobs();
await startJobs();
break;
case settings.USER_DIRECTORY_KEY:
if (value.enabled) await userdirectory.start();
else await userdirectory.stop();
break;
default:
break;
}
+63 -28
View File
@@ -11,7 +11,7 @@ exports = module.exports = {
const assert = require('assert'),
BoxError = require('./boxerror.js'),
constants = require('./constants.js'),
debug = require('debug')('box:userdirectory'),
debug = require('debug')('box:directoryserver'),
dns = require('./dns.js'),
domains = require('./domains.js'),
eventlog = require('./eventlog.js'),
@@ -23,6 +23,7 @@ const assert = require('assert'),
reverseproxy = require('./reverseproxy.js'),
safe = require('safetydance'),
settings = require('./settings.js'),
speakeasy = require('speakeasy'),
shell = require('./shell.js'),
users = require('./users.js'),
util = require('util'),
@@ -32,8 +33,6 @@ let gServer = null;
const NOOP = function () {};
const GROUP_USERS_DN = 'cn=users,ou=groups,dc=cloudron';
const GROUP_ADMINS_DN = 'cn=admins,ou=groups,dc=cloudron';
const SET_LDAP_ALLOWLIST_CMD = path.join(__dirname, 'scripts/setldapallowlist.sh');
async function validateConfig(config) {
@@ -68,6 +67,8 @@ async function applyConfig(config) {
const [error] = await safe(shell.promises.sudo('setLdapAllowlist', [ SET_LDAP_ALLOWLIST_CMD ], {}));
if (error) throw new BoxError(BoxError.IPTABLES_ERROR, `Error setting ldap allowlist: ${error.message}`);
if (config.enabled) await start(); else await stop();
}
// helper function to deal with pagination
@@ -142,23 +143,43 @@ async function authorize(req, res, next) {
return next();
}
// https://ldapwiki.com/wiki/RootDSE / RFC 4512 - ldapsearch -x -h "${CLOUDRON_LDAP_SERVER}" -p "${CLOUDRON_LDAP_PORT}" -b "" -s base
// ldapjs seems to call this handler for everything when search === ''
async function maybeRootDSE(req, res, next) {
debug(`maybeRootDSE: requested with scope:${req.scope} dn:${req.dn.toString()}`);
if (req.scope !== 'base') return next(new ldap.NoSuchObjectError()); // per the spec, rootDSE search require base scope
if (!req.dn || req.dn.toString() !== '') return next(new ldap.NoSuchObjectError());
res.send({
dn: '',
attributes: {
objectclass: [ 'RootDSE', 'top', 'OpenLDAProotDSE' ],
supportedLDAPVersion: '3',
vendorName: 'Cloudron LDAP',
vendorVersion: '1.0.0'
}
});
res.end();
}
async function userSearch(req, res, next) {
debug('user search: dn %s, scope %s, filter %s (from %s)', req.dn.toString(), req.scope, req.filter.toString(), req.connection.ldap.id);
const [error, result] = await safe(users.list());
const [error, allUsers] = await safe(users.list());
if (error) return next(new ldap.OperationsError(error.toString()));
const [groupsError, allGroups] = await safe(groups.listWithMembers());
if (groupsError) return next(new ldap.OperationsError(error.toString()));
let results = [];
// send user objects
result.forEach(function (user) {
for (const user of allUsers) {
// skip entries with empty username. Some apps like owncloud can't deal with this
if (!user.username) return;
if (!user.username) continue;
const dn = ldap.parseDN('cn=' + user.id + ',ou=users,dc=cloudron');
const memberof = [ GROUP_USERS_DN ];
if (users.compareRoles(user.role, users.ROLE_ADMIN) >= 0) memberof.push(GROUP_ADMINS_DN);
const dn = ldap.parseDN(`cn=${user.id},ou=users,dc=cloudron`);
const displayName = user.displayName || user.username || ''; // displayName can be empty and username can be null
const nameParts = displayName.split(' ');
@@ -179,10 +200,12 @@ async function userSearch(req, res, next) {
givenName: firstName,
username: user.username,
samaccountname: user.username, // to support ActiveDirectory clients
memberof: memberof
memberof: allGroups.filter(function (g) { return g.userIds.indexOf(user.id) !== -1; }).map(function (g) { return g.name; })
}
};
if (user.twoFactorAuthenticationEnabled) obj.attributes.twoFactorAuthenticationEnabled = true;
// http://www.zytrax.com/books/ldap/ape/core-schema.html#sn has 'name' as SUP which is a DirectoryString
// which is required to have atleast one character if present
if (lastName.length !== 0) obj.attributes.sn = lastName;
@@ -194,7 +217,7 @@ async function userSearch(req, res, next) {
if ((req.dn.equals(dn) || req.dn.parentOf(dn)) && lowerCaseFilter.matches(obj.attributes)) {
results.push(obj);
}
});
}
finalSend(results, req, res, next);
}
@@ -202,23 +225,24 @@ async function userSearch(req, res, next) {
async function groupSearch(req, res, next) {
debug('group search: dn %s, scope %s, filter %s (from %s)', req.dn.toString(), req.scope, req.filter.toString(), req.connection.ldap.id);
const [error, result] = await safe(users.list());
const [error, allUsers] = await safe(users.list());
if (error) return next(new ldap.OperationsError(error.toString()));
const results = [];
let [errorGroups, resultGroups] = await safe(groups.listWithMembers());
let [errorGroups, allGroups] = await safe(groups.listWithMembers());
if (errorGroups) return next(new ldap.OperationsError(errorGroups.toString()));
resultGroups.forEach(function (group) {
const dn = ldap.parseDN('cn=' + group.name + ',ou=groups,dc=cloudron');
const members = group.userIds.filter(function (uid) { return result.map(function (u) { return u.id; }).indexOf(uid) !== -1; });
for (const group of allGroups) {
const dn = ldap.parseDN(`cn=${group.name},ou=groups,dc=cloudron`);
const members = group.userIds.filter(function (uid) { return allUsers.map(function (u) { return u.id; }).indexOf(uid) !== -1; });
const obj = {
dn: dn.toString(),
attributes: {
objectclass: ['group'],
cn: group.name,
gidnumber: group.id,
memberuid: members
}
};
@@ -230,7 +254,7 @@ async function groupSearch(req, res, next) {
if ((req.dn.equals(dn) || req.dn.parentOf(dn)) && lowerCaseFilter.matches(obj.attributes)) {
results.push(obj);
}
});
}
finalSend(results, req, res, next);
}
@@ -238,12 +262,15 @@ async function groupSearch(req, res, next) {
// Will attach req.user if successful
async function userAuth(req, res, next) {
// extract the common name which might have different attribute names
const attributeName = Object.keys(req.dn.rdns[0].attrs)[0];
const commonName = req.dn.rdns[0].attrs[attributeName].value;
const cnAttributeName = Object.keys(req.dn.rdns[0].attrs)[0];
const commonName = req.dn.rdns[0].attrs[cnAttributeName].value;
if (!commonName) return next(new ldap.NoSuchObjectError(req.dn.toString()));
const TOTPTOKEN_ATTRIBUTE_NAME = 'totptoken'; // This has to be in-sync with externalldap.js
const totpToken = req.dn.rdns[0].attrs[TOTPTOKEN_ATTRIBUTE_NAME] ? req.dn.rdns[0].attrs[TOTPTOKEN_ATTRIBUTE_NAME].value : null;
let verifyFunc;
if (attributeName === 'mail') {
if (cnAttributeName === 'mail') {
verifyFunc = users.verifyWithEmail;
} else if (commonName.indexOf('@') !== -1) { // if mail is specified, enforce mail check
verifyFunc = users.verifyWithEmail;
@@ -258,6 +285,12 @@ async function userAuth(req, res, next) {
if (error && error.reason === BoxError.INVALID_CREDENTIALS) return next(new ldap.InvalidCredentialsError(req.dn.toString()));
if (error) return next(new ldap.OperationsError(error.message));
// currently this is only optional if totpToken is provided and user has 2fa enabled
if (totpToken && user.twoFactorAuthenticationEnabled) {
const verified = speakeasy.totp.verify({ secret: user.twoFactorAuthenticationSecret, encoding: 'base32', token: totpToken, window: 2 });
if (!verified) return next(new ldap.InvalidCredentialsError(req.dn.toString()));
}
req.user = user;
next();
@@ -277,12 +310,12 @@ async function start() {
};
const domainObject = await domains.get(settings.dashboardDomain());
const dashboardFqdn = dns.fqdn(constants.DASHBOARD_LOCATION, domainObject);
const bundle = await reverseproxy.getCertificatePath(dashboardFqdn, domainObject.domain);
const dashboardFqdn = dns.fqdn(constants.DASHBOARD_SUBDOMAIN, domainObject);
const certificatePath = await reverseproxy.getCertificatePath(dashboardFqdn, domainObject.domain);
gServer = ldap.createServer({
certificate: fs.readFileSync(bundle.certFilePath, 'utf8'),
key: fs.readFileSync(bundle.keyFilePath, 'utf8'),
certificate: fs.readFileSync(certificatePath.certFilePath, 'utf8'),
key: fs.readFileSync(certificatePath.keyFilePath, 'utf8'),
log: logger
});
@@ -293,12 +326,12 @@ async function start() {
gServer.bind('ou=system,dc=cloudron', async function(req, res, next) {
debug('system bind: %s (from %s)', req.dn.toString(), req.connection.ldap.id);
const tmp = await settings.getUserDirectoryConfig();
const tmp = await settings.getDirectoryServerConfig();
if (!req.dn.equals(constants.USER_DIRECTORY_LDAP_DN)) return next(new ldap.InvalidCredentialsError(req.dn.toString()));
if (req.credentials !== tmp.secret) return next(new ldap.InvalidCredentialsError(req.dn.toString()));
req.user = { user: 'userDirectoryAdmin' };
req.user = { user: 'directoryServerAdmin' };
res.end();
@@ -311,11 +344,13 @@ async function start() {
gServer.bind('ou=users,dc=cloudron', userAuth, async function (req, res) {
assert.strictEqual(typeof req.user, 'object');
await eventlog.upsertLoginEvent(eventlog.ACTION_USER_LOGIN, { authType: 'userdirectory', id: req.connection.ldap.id }, { userId: req.user.id, user: users.removePrivateFields(req.user) });
await eventlog.upsertLoginEvent(req.user.ghost ? eventlog.ACTION_USER_LOGIN_GHOST : eventlog.ACTION_USER_LOGIN, { authType: 'directoryserver', id: req.connection.ldap.id }, { userId: req.user.id, user: users.removePrivateFields(req.user) });
res.end();
});
gServer.search('', maybeRootDSE); // when '', it seems the callback is called for everything else
// just log that an attempt was made to unknown route, this helps a lot during app packaging
gServer.use(function(req, res, next) {
debug('not handled: dn %s, scope %s, filter %s (from %s)', req.dn ? req.dn.toString() : '-', req.scope, req.filter ? req.filter.toString() : '-', req.connection.ldap.id);
+9 -9
View File
@@ -76,11 +76,11 @@ function validateHostname(subdomain, domainObject) {
const hostname = fqdn(subdomain, domainObject);
const RESERVED_LOCATIONS = [
constants.SMTP_LOCATION,
constants.IMAP_LOCATION
const RESERVED_SUBDOMAINS = [
constants.SMTP_SUBDOMAIN,
constants.IMAP_SUBDOMAIN
];
if (RESERVED_LOCATIONS.indexOf(subdomain) !== -1) return new BoxError(BoxError.BAD_FIELD, `subdomain '${subdomain}' is reserved`);
if (RESERVED_SUBDOMAINS.indexOf(subdomain) !== -1) return new BoxError(BoxError.BAD_FIELD, `subdomain '${subdomain}' is reserved`);
if (hostname === settings.dashboardFqdn()) return new BoxError(BoxError.BAD_FIELD, `subdomain '${subdomain}' is reserved`);
@@ -184,11 +184,11 @@ async function waitForDnsRecord(subdomain, domain, type, value, options) {
await api(domainObject.provider).wait(domainObject, subdomain, type, value, options);
}
function makeWildcard(vhost) {
assert.strictEqual(typeof vhost, 'string');
function makeWildcard(fqdn) {
assert.strictEqual(typeof fqdn, 'string');
// if the vhost is like *.example.com, this function will do nothing
let parts = vhost.split('.');
// if the fqdn is like *.example.com, this function will do nothing
const parts = fqdn.split('.');
parts[0] = '*';
return parts.join('.');
}
@@ -295,7 +295,7 @@ async function syncDnsRecords(options, progressCallback) {
progress += Math.round(100/(1+allDomains.length));
let locations = [];
if (domain.domain === settings.dashboardDomain()) locations.push({ subdomain: constants.DASHBOARD_LOCATION, domain: settings.dashboardDomain() });
if (domain.domain === settings.dashboardDomain()) locations.push({ subdomain: constants.DASHBOARD_SUBDOMAIN, domain: settings.dashboardDomain() });
if (domain.domain === settings.mailDomain() && settings.mailFqdn() !== settings.dashboardFqdn()) locations.push({ subdomain: mailSubdomain, domain: settings.mailDomain() });
for (const app of allApps) {
+6
View File
@@ -205,6 +205,11 @@ async function wait(domainObject, subdomain, type, value, options) {
await waitForDns(fqdn, domainObject.zoneName, type, value, options);
}
// https://stackoverflow.com/questions/14313183/javascript-regex-how-do-i-check-if-the-string-is-ascii-only
function isASCII(str) {
return /^[\x00-\x7F]*$/.test(str);
}
async function verifyDomainConfig(domainObject) {
assert.strictEqual(typeof domainObject, 'object');
@@ -212,6 +217,7 @@ async function verifyDomainConfig(domainObject) {
zoneName = domainObject.zoneName;
if (!domainConfig.token || typeof domainConfig.token !== 'string') throw new BoxError(BoxError.BAD_FIELD, 'token must be a non-empty string');
if (!isASCII(domainConfig.token)) throw new BoxError(BoxError.BAD_FIELD, 'token contains invalid characters');
const ip = '127.0.0.1';
+1 -1
View File
@@ -178,7 +178,7 @@ async function verifyDomainConfig(domainObject) {
if (error && error.code === 'ENOTFOUND') throw new BoxError(BoxError.BAD_FIELD, 'Unable to resolve nameservers for this domain');
if (error || !nameservers) throw new BoxError(BoxError.BAD_FIELD, error ? error.message : 'Unable to get nameservers');
if (!nameservers.every(function (n) { return n.toLowerCase().indexOf('.domaincontrol.com') !== -1; })) {
if (!nameservers.every(function (n) { return n.toLowerCase().indexOf('.domaincontrol.com') !== -1 || n.toLowerCase().indexOf('.secureserver.net') !== -1; })) {
debug('verifyDomainConfig: %j does not contain GoDaddy NS', nameservers);
throw new BoxError(BoxError.BAD_FIELD, 'Domain nameservers are not set to GoDaddy');
}
+1 -1
View File
@@ -13,7 +13,7 @@ exports = module.exports = {
const assert = require('assert'),
BoxError = require('../boxerror.js'),
constants = require('../constants.js'),
debug = require('debug')('box:dns/digitalocean'),
debug = require('debug')('box:dns/hetzner'),
dig = require('../dig.js'),
dns = require('../dns.js'),
safe = require('safetydance'),
+10 -3
View File
@@ -8,6 +8,7 @@ exports = module.exports = {
ping,
info,
df,
downloadImage,
createContainer,
startContainer,
@@ -204,18 +205,18 @@ async function getAddonMounts(app) {
break;
}
case 'tls': {
const bundle = await reverseProxy.getCertificatePath(app.fqdn, app.domain);
const certificatePath = await reverseProxy.getCertificatePath(app.fqdn, app.domain);
mounts.push({
Target: '/etc/certs/tls_cert.pem',
Source: bundle.certFilePath,
Source: certificatePath.certFilePath,
Type: 'bind',
ReadOnly: true
});
mounts.push({
Target: '/etc/certs/tls_key.pem',
Source: bundle.keyFilePath,
Source: certificatePath.keyFilePath,
Type: 'bind',
ReadOnly: true
});
@@ -630,6 +631,12 @@ async function info() {
return result;
}
async function df() {
const [error, result] = await safe(gConnection.df());
if (error) throw new BoxError(BoxError.DOCKER_ERROR, 'Error connecting to docker');
return result;
}
async function update(name, memory, memorySwap) {
assert.strictEqual(typeof name, 'string');
assert.strictEqual(typeof memory, 'number');
+20 -25
View File
@@ -77,13 +77,13 @@ async function verifyDomainConfig(domainConfig, domain, zoneName, provider) {
if (!backend) throw new BoxError(BoxError.BAD_FIELD, 'Invalid provider');
const domainObject = { config: domainConfig, domain: domain, zoneName: zoneName };
const [error, result] = await safe(api(provider).verifyDomainConfig(domainObject));
if (error && error.reason === BoxError.ACCESS_DENIED) return { error: new BoxError(BoxError.BAD_FIELD, `Access denied: ${error.message}`) };
if (error && error.reason === BoxError.NOT_FOUND) return { error: new BoxError(BoxError.BAD_FIELD, `Zone not found: ${error.message}`) };
if (error && error.reason === BoxError.EXTERNAL_ERROR) return { error: new BoxError(BoxError.BAD_FIELD, `Configuration error: ${error.message}`) };
if (error) return { error };
const [error, sanitizedConfig] = await safe(api(provider).verifyDomainConfig(domainObject));
if (error && error.reason === BoxError.ACCESS_DENIED) throw new BoxError(BoxError.BAD_FIELD, `Access denied: ${error.message}`);
if (error && error.reason === BoxError.NOT_FOUND) throw new BoxError(BoxError.BAD_FIELD, `Zone not found: ${error.message}`);
if (error && error.reason === BoxError.EXTERNAL_ERROR) throw new BoxError(BoxError.BAD_FIELD, `Configuration error: ${error.message}`);
if (error) throw error;
return { error: null, sanitizedConfig: result };
return sanitizedConfig;
}
function validateTlsConfig(tlsConfig, dnsProvider) {
@@ -151,12 +151,11 @@ async function add(domain, data, auditSource) {
dkimSelector = `cloudron-${suffix}`;
}
const result = await verifyDomainConfig(config, domain, zoneName, provider);
if (result.error) throw result.error;
const sanitizedConfig = await verifyDomainConfig(config, domain, zoneName, provider);
let queries = [
const queries = [
{ query: 'INSERT INTO domains (domain, zoneName, provider, configJson, tlsConfigJson, fallbackCertificateJson) VALUES (?, ?, ?, ?, ?, ?)',
args: [ domain, zoneName, provider, JSON.stringify(result.sanitizedConfig), JSON.stringify(tlsConfig), JSON.stringify(fallbackCertificate) ] },
args: [ domain, zoneName, provider, JSON.stringify(sanitizedConfig), JSON.stringify(tlsConfig), JSON.stringify(fallbackCertificate) ] },
{ query: 'INSERT INTO mail (domain, dkimKeyJson, dkimSelector) VALUES (?, ?, ?)', args: [ domain, JSON.stringify(dkimKey), dkimSelector || 'cloudron' ] },
];
@@ -195,7 +194,6 @@ async function setConfig(domain, data, auditSource) {
assert.strictEqual(typeof auditSource, 'object');
let { zoneName, provider, config, fallbackCertificate, tlsConfig } = data;
let error;
if (settings.isDemo() && (domain === settings.dashboardDomain())) throw new BoxError(BoxError.CONFLICT, 'Not allowed in demo mode');
@@ -211,16 +209,15 @@ async function setConfig(domain, data, auditSource) {
if (error) throw error;
}
error = validateTlsConfig(tlsConfig, provider);
if (error) throw error;
const tlsConfigError = validateTlsConfig(tlsConfig, provider);
if (tlsConfigError) throw tlsConfigError;
if (provider === domainObject.provider) api(provider).injectPrivateFields(config, domainObject.config);
const result = await verifyDomainConfig(config, domain, zoneName, provider);
if (result.error) throw result.error;
const sanitizedConfig = await verifyDomainConfig(config, domain, zoneName, provider);
const newData = {
config: result.sanitizedConfig,
config: sanitizedConfig,
zoneName,
provider,
tlsConfig,
@@ -228,7 +225,7 @@ async function setConfig(domain, data, auditSource) {
if (fallbackCertificate) newData.fallbackCertificate = fallbackCertificate;
let args = [ ], fields = [ ];
const args = [], fields = [];
for (const k in newData) {
if (k === 'config' || k === 'tlsConfig' || k === 'fallbackCertificate') { // json fields
fields.push(`${k}Json = ?`);
@@ -240,9 +237,8 @@ async function setConfig(domain, data, auditSource) {
}
args.push(domain);
[error] = await safe(database.query('UPDATE domains SET ' + fields.join(', ') + ' WHERE domain=?', args));
if (error && error.reason === BoxError.NOT_FOUND) throw new BoxError(BoxError.NOT_FOUND, 'Domain not found');
if (error) throw new BoxError(BoxError.DATABASE_ERROR, error);
const result = await database.query('UPDATE domains SET ' + fields.join(', ') + ' WHERE domain=?', args);
if (result.affectedRows === 0) throw new BoxError(BoxError.NOT_FOUND, 'Domain not found');
if (!fallbackCertificate) return;
@@ -256,12 +252,11 @@ async function setWellKnown(domain, wellKnown, auditSource) {
assert.strictEqual(typeof wellKnown, 'object');
assert.strictEqual(typeof auditSource, 'object');
let error = validateWellKnown(wellKnown);
if (error) throw error;
const wellKnownError = validateWellKnown(wellKnown);
if (wellKnownError) throw wellKnownError;
[error] = await safe(database.query('UPDATE domains SET wellKnownJson = ? WHERE domain=?', [ JSON.stringify(wellKnown), domain ]));
if (error && error.reason === BoxError.NOT_FOUND) throw new BoxError(BoxError.NOT_FOUND, 'Domain not found');
if (error) throw new BoxError(BoxError.DATABASE_ERROR, error);
const result = await database.query('UPDATE domains SET wellKnownJson = ? WHERE domain=?', [ JSON.stringify(wellKnown), domain ]);
if (result.affectedRows === 0) throw new BoxError(BoxError.NOT_FOUND, 'Domain not found');
await eventlog.add(eventlog.ACTION_DOMAIN_UPDATE, auditSource, { domain, wellKnown });
}
+2 -2
View File
@@ -36,8 +36,8 @@ async function sync(auditSource) {
}
debug(`refreshDNS: updating IP from ${info.ipv4} to ipv4: ${ipv4} (changed: ${ipv4Changed}) ipv6: ${ipv6} (changed: ${ipv6Changed})`);
if (ipv4Changed) await dns.upsertDnsRecords(constants.DASHBOARD_LOCATION, settings.dashboardDomain(), 'A', [ ipv4 ]);
if (ipv6Changed) await dns.upsertDnsRecords(constants.DASHBOARD_LOCATION, settings.dashboardDomain(), 'AAAA', [ ipv6 ]);
if (ipv4Changed) await dns.upsertDnsRecords(constants.DASHBOARD_SUBDOMAIN, settings.dashboardDomain(), 'A', [ ipv4 ]);
if (ipv6Changed) await dns.upsertDnsRecords(constants.DASHBOARD_SUBDOMAIN, settings.dashboardDomain(), 'AAAA', [ ipv6 ]);
const result = await apps.list();
for (const app of result) {
+1
View File
@@ -69,6 +69,7 @@ exports = module.exports = {
ACTION_USER_ADD: 'user.add',
ACTION_USER_LOGIN: 'user.login',
ACTION_USER_LOGIN_GHOST: 'user.login.ghost',
ACTION_USER_LOGOUT: 'user.logout',
ACTION_USER_REMOVE: 'user.remove',
ACTION_USER_UPDATE: 'user.update',
+33 -2
View File
@@ -2,6 +2,7 @@
exports = module.exports = {
verifyPassword,
verifyPasswordAndTotpToken,
maybeCreateUser,
testConfig,
@@ -44,6 +45,7 @@ function translateUser(ldapConfig, ldapUser) {
return {
username: ldapUser[ldapConfig.usernameField].toLowerCase(),
email: ldapUser.mail || ldapUser.mailPrimaryAddress,
twoFactorAuthenticationEnabled: !!ldapUser.twoFactorAuthenticationEnabled,
displayName: ldapUser.displayName || ldapUser.cn // user.giveName + ' ' + user.sn
};
}
@@ -254,8 +256,11 @@ async function maybeCreateUser(identifier) {
throw error;
}
// fetch the full record
return await users.get(userId);
// fetch the full record and amend potential twoFA settings
const newUser = await users.get(userId);
if (user.twoFactorAuthenticationEnabled) newUser.twoFactorAuthenticationEnabled = true;
return newUser;
}
async function verifyPassword(user, password) {
@@ -279,6 +284,32 @@ async function verifyPassword(user, password) {
return translateUser(externalLdapConfig, ldapUsers[0]);
}
async function verifyPasswordAndTotpToken(user, password, totpToken) {
assert.strictEqual(typeof user, 'object');
assert.strictEqual(typeof password, 'string');
assert.strictEqual(typeof totpToken, 'string');
const externalLdapConfig = await settings.getExternalLdapConfig();
if (externalLdapConfig.provider === 'noop') throw new BoxError(BoxError.BAD_STATE, 'not enabled');
const ldapUsers = await ldapUserSearch(externalLdapConfig, { filter: `${externalLdapConfig.usernameField}=${user.username}` });
if (ldapUsers.length === 0) throw new BoxError(BoxError.NOT_FOUND);
if (ldapUsers.length > 1) throw new BoxError(BoxError.CONFLICT);
const client = await getClient(externalLdapConfig, { bind: false });
// inject totptoken into first attribute
const rdns = ldapUsers[0].dn.split(',');
const totpTokenDn = `${rdns[0]}+totptoken=${totpToken},` + rdns.slice(1).join(',');
const [error] = await safe(util.promisify(client.bind.bind(client))(totpTokenDn, password));
client.unbind();
if (error instanceof ldap.InvalidCredentialsError) throw new BoxError(BoxError.INVALID_CREDENTIALS);
if (error) throw new BoxError(BoxError.EXTERNAL_ERROR, error);
return translateUser(externalLdapConfig, ldapUsers[0]);
}
async function startSyncer() {
const externalLdapConfig = await settings.getExternalLdapConfig();
if (externalLdapConfig.provider === 'noop') throw new BoxError(BoxError.BAD_STATE, 'not enabled');
+124
View File
@@ -0,0 +1,124 @@
'use strict';
exports = module.exports = {
getSystem,
getContainerStats
};
const apps = require('./apps.js'),
assert = require('assert'),
BoxError = require('./boxerror.js'),
docker = require('./docker.js'),
os = require('os'),
safe = require('safetydance'),
services = require('./services.js'),
superagent = require('superagent');
// for testing locally: curl 'http://${graphite-ip}:8000/graphite-web/render?format=json&from=-1min&target=absolute(collectd.localhost.du-docker.capacity-usage)'
// the datapoint is (value, timestamp) https://graphite.readthedocs.io/en/latest/
async function getGraphiteUrl() {
const [error, result] = await safe(docker.inspect('graphite'));
if (error && error.reason === BoxError.NOT_FOUND) return { status: exports.SERVICE_STATUS_STOPPED };
if (error) throw error;
const ip = safe.query(result, 'NetworkSettings.Networks.cloudron.IPAddress', null);
if (!ip) throw new BoxError(BoxError.INACTIVE, 'Error getting IP of graphite service');
return `http://${ip}:8000/graphite-web/render`;
}
async function getContainerStats(name, fromMinutes, noNullPoints) {
assert.strictEqual(typeof name, 'string');
assert.strictEqual(typeof fromMinutes, 'number');
assert.strictEqual(typeof noNullPoints, 'boolean');
const timeBucketSize = fromMinutes > (24 * 60) ? (6*60) : 5;
const graphiteUrl = await getGraphiteUrl();
const targets = [
`summarize(collectd.localhost.docker-stats-${name}.gauge-cpu-perc, "${timeBucketSize}min", "avg")`,
`summarize(collectd.localhost.docker-stats-${name}.gauge-mem-used, "${timeBucketSize}min", "avg")`,
// `summarize(collectd.localhost.docker-stats-${name}.gauge-mem-max, "${timeBucketSize}min", "avg")`,
`summarize(collectd.localhost.docker-stats-${name}.counter-blockio-read, "${timeBucketSize}min", "sum")`,
`summarize(collectd.localhost.docker-stats-${name}.counter-blockio-write, "${timeBucketSize}min", "sum")`,
`summarize(collectd.localhost.docker-stats-${name}.counter-network-read, "${timeBucketSize}min", "sum")`,
`summarize(collectd.localhost.docker-stats-${name}.counter-network-write, "${timeBucketSize}min", "sum")`,
`summarize(collectd.localhost.docker-stats-${name}.gauge-blockio-read, "${fromMinutes}min", "max")`,
`summarize(collectd.localhost.docker-stats-${name}.gauge-blockio-write, "${fromMinutes}min", "max")`,
`summarize(collectd.localhost.docker-stats-${name}.gauge-network-read, "${fromMinutes}min", "max")`,
`summarize(collectd.localhost.docker-stats-${name}.gauge-network-write, "${fromMinutes}min", "max")`,
];
const results = [];
for (const target of targets) {
const query = {
target: target,
format: 'json',
from: `-${fromMinutes}min`,
until: 'now',
noNullPoints: !!noNullPoints
};
const [error, response] = await safe(superagent.get(graphiteUrl).query(query).timeout(30 * 1000).ok(() => true));
if (error) throw new BoxError(BoxError.NETWORK_ERROR, error.message);
if (response.status !== 200) throw new BoxError(BoxError.EXTERNAL_ERROR, `Unknown error with ${target}: ${response.status} ${response.text}`);
results.push(response.body[0] && response.body[0].datapoints ? response.body[0].datapoints : []);
}
// results are datapoints[[value, ts], [value, ts], ...];
return {
cpu: results[0],
memory: results[1],
blockRead: results[2],
blockWrite: results[3],
networkRead: results[4],
networkWrite: results[5],
blockReadTotal: results[6][0] && results[6][0][0] ? results[6][0][0] : 0,
blockWriteTotal: results[7][0] && results[7][0][0] ? results[7][0][0] : 0,
networkReadTotal: results[8][0] && results[8][0][0] ? results[8][0][0] : 0,
networkWriteTotal: results[9][0] && results[9][0][0] ? results[9][0][0] : 0,
cpuCount: os.cpus().length
};
}
async function getSystem(fromMinutes, noNullPoints) {
assert.strictEqual(typeof fromMinutes, 'number');
assert.strictEqual(typeof noNullPoints, 'boolean');
const timeBucketSize = fromMinutes > (24 * 60) ? (6*60) : 5;
const graphiteUrl = await getGraphiteUrl();
const cpuQuery = `summarize(sum(collectd.localhost.aggregation-cpu-sum.cpu-system, collectd.localhost.aggregation-cpu-sum.cpu-user), "${timeBucketSize}min", "avg")`;
const memoryQuery = `summarize(collectd.localhost.memory.memory-used, "${timeBucketSize}min", "avg")`;
const query = {
target: [ cpuQuery, memoryQuery ],
format: 'json',
from: `-${fromMinutes}min`,
until: 'now'
};
const [memCpuError, memCpuResponse] = await safe(superagent.get(graphiteUrl).query(query).timeout(30 * 1000).ok(() => true));
if (memCpuError) throw new BoxError(BoxError.NETWORK_ERROR, memCpuError.message);
if (memCpuResponse.status !== 200) throw new BoxError(BoxError.EXTERNAL_ERROR, `Unknown error: ${memCpuResponse.status} ${memCpuResponse.text}`);
const appResponses = {};
for (const app of await apps.list()) {
appResponses[app.id] = await getContainerStats(app.id, fromMinutes, noNullPoints);
}
const serviceResponses = {};
for (const serviceId of await services.listServices()) {
serviceResponses[serviceId] = await getContainerStats(serviceId, fromMinutes, noNullPoints);
}
return {
cpu: memCpuResponse.body[0] && memCpuResponse.body[0].datapoints ? memCpuResponse.body[0].datapoints : [],
memory: memCpuResponse.body[1] && memCpuResponse.body[1].datapoints ? memCpuResponse.body[1].datapoints : [],
apps: appResponses,
services: serviceResponses,
cpuCount: os.cpus().length
};
}
+7 -7
View File
@@ -6,7 +6,7 @@
exports = module.exports = {
// a version change recreates all containers with latest docker config
'version': '49.0.0',
'version': '49.2.0',
'baseImages': [
{ repo: 'cloudron/base', tag: 'cloudron/base:3.2.0@sha256:ba1d566164a67c266782545ea9809dc611c4152e27686fd14060332dd88263ea' }
@@ -16,12 +16,12 @@ exports = module.exports = {
// docker inspect --format='{{index .RepoDigests 0}}' $IMAGE to get the sha256
'images': {
'turn': { repo: 'cloudron/turn', tag: 'cloudron/turn:1.4.0@sha256:45817f1631992391d585f171498d257487d872480fd5646723a2b956cc4ef15d' },
'mysql': { repo: 'cloudron/mysql', tag: 'cloudron/mysql:3.2.1@sha256:75cef64ba4917ba9ec68bc0c9d9ba3a9eeae00a70173cd6d81cc6118038737d9' },
'postgresql': { repo: 'cloudron/postgresql', tag: 'cloudron/postgresql:4.3.1@sha256:b0c564d097b765d4a639330843e2e813d2c87fc8ed34b7df7550bf2c6df0012c' },
'mongodb': { repo: 'cloudron/mongodb', tag: 'cloudron/mongodb:4.2.1@sha256:f7f689beea07b1c6a9503a48f6fb38ef66e5b22f59fc585a92842a6578b33d46' },
'redis': { repo: 'cloudron/redis', tag: 'cloudron/redis:3.3.0@sha256:89c4e8083631b6d16b5d630d9b27f8ecf301c62f81219d77bd5948a1f4a4375c' },
'mail': { repo: 'cloudron/mail', tag: 'cloudron/mail:3.6.1@sha256:b8b93f007105080d4812a05648e6bc5e15c95c63f511c829cbc14a163d9ea029' },
'graphite': { repo: 'cloudron/graphite', tag: 'cloudron/graphite:3.1.0@sha256:30ec3a01964a1e01396acf265183997c3e17fb07eac1a82b979292cc7719ff4b' },
'mysql': { repo: 'cloudron/mysql', tag: 'cloudron/mysql:3.2.2@sha256:8648ca5a16fcdec72799b919c5f62419fd19e922e3d98d02896b921ae6127ef4' },
'postgresql': { repo: 'cloudron/postgresql', tag: 'cloudron/postgresql:4.3.4@sha256:84effb12e93d4e6467fedf3a426989980927ef90be61e73bde43476eebadf2a8' },
'mongodb': { repo: 'cloudron/mongodb', tag: 'cloudron/mongodb:4.2.2@sha256:df928d7dce1ac6454fc584787fa863f6d5e7ee0abb775dde5916a555fc94c3c7' },
'redis': { repo: 'cloudron/redis', tag: 'cloudron/redis:3.3.1@sha256:383e11a5c7a54d17eb6bbceb0ffa92f486167be6ea9978ec745c8c8e9b7dfb19' },
'mail': { repo: 'cloudron/mail', tag: 'cloudron/mail:3.7.0@sha256:44df70c8030cb9da452568c32fae7cae447e3b98cf48fdbc7b27a2466e706473' },
'graphite': { repo: 'cloudron/graphite', tag: 'cloudron/graphite:3.1.0@sha256:182e5cae69fbddc703cb9f91be909452065c7ae159e9836cc88317c7a00f0e62' },
'sftp': { repo: 'cloudron/sftp', tag: 'cloudron/sftp:3.6.1@sha256:ba4b9a1fe274c0ef0a900e5d0deeb8f3da08e118798d1d90fbf995cc0cf6e3a3' }
}
};
+32 -26
View File
@@ -25,9 +25,6 @@ let gServer = null;
const NOOP = function () {};
const GROUP_USERS_DN = 'cn=users,ou=groups,dc=cloudron';
const GROUP_ADMINS_DN = 'cn=admins,ou=groups,dc=cloudron';
// Will attach req.app if successful
async function authenticateApp(req, res, next) {
const sourceIp = req.connection.ldap.id.split(':')[0];
@@ -150,6 +147,9 @@ async function userSearch(req, res, next) {
const [error, result] = await safe(getUsersWithAccessToApp(req));
if (error) return next(new ldap.OperationsError(error.toString()));
const [groupsError, allGroups] = await safe(groups.listWithMembers());
if (groupsError) return next(new ldap.OperationsError(error.toString()));
let results = [];
// send user objects
@@ -159,9 +159,6 @@ async function userSearch(req, res, next) {
const dn = ldap.parseDN('cn=' + user.id + ',ou=users,dc=cloudron');
const memberof = [ GROUP_USERS_DN ];
if (users.compareRoles(user.role, users.ROLE_ADMIN) >= 0) memberof.push(GROUP_ADMINS_DN);
const displayName = user.displayName || user.username || ''; // displayName can be empty and username can be null
const nameParts = displayName.split(' ');
const firstName = nameParts[0];
@@ -181,7 +178,7 @@ async function userSearch(req, res, next) {
givenName: firstName,
username: user.username,
samaccountname: user.username, // to support ActiveDirectory clients
memberof: memberof
memberof: allGroups.filter(function (g) { return g.userIds.indexOf(user.id) !== -1; }).map(function (g) { return g.name; })
}
};
@@ -204,9 +201,6 @@ async function userSearch(req, res, next) {
async function groupSearch(req, res, next) {
debug('group search: dn %s, scope %s, filter %s (from %s)', req.dn.toString(), req.scope, req.filter.toString(), req.connection.ldap.id);
const [error, usersWithAccess] = await safe(getUsersWithAccessToApp(req));
if (error) return next(new ldap.OperationsError(error.toString()));
const results = [];
let [errorGroups, resultGroups] = await safe(groups.listWithMembers());
@@ -217,15 +211,15 @@ async function groupSearch(req, res, next) {
}
resultGroups.forEach(function (group) {
const dn = ldap.parseDN('cn=' + group.name + ',ou=groups,dc=cloudron');
const members = group.userIds.filter(function (uid) { return usersWithAccess.map(function (u) { return u.id; }).indexOf(uid) !== -1; });
const dn = ldap.parseDN(`cn=${group.name},ou=groups,dc=cloudron`);
const obj = {
dn: dn.toString(),
attributes: {
objectclass: ['group'],
cn: group.name,
memberuid: members
gidnumber: group.id,
memberuid: group.userIds
}
};
@@ -274,25 +268,35 @@ async function groupAdminsCompare(req, res, next) {
async function mailboxSearch(req, res, next) {
debug('mailbox search: dn %s, scope %s, filter %s (from %s)', req.dn.toString(), req.scope, req.filter.toString(), req.connection.ldap.id);
// if cn is set we only search for one mailbox specifically
// if cn is set OR filter is mail= we only search for one mailbox specifically
let email, dn;
if (req.dn.rdns[0].attrs.cn) {
const email = req.dn.rdns[0].attrs.cn.value.toLowerCase();
email = req.dn.rdns[0].attrs.cn.value.toLowerCase();
dn = req.dn.toString();
} else if (req.filter instanceof ldap.EqualityFilter && req.filter.attribute === 'mail') {
email = req.filter.value.toLowerCase();
dn = `cn=${email},${req.dn.toString()}`;
}
if (email) {
const parts = email.split('@');
if (parts.length !== 2) return next(new ldap.NoSuchObjectError(req.dn.toString()));
if (parts.length !== 2) return next(new ldap.NoSuchObjectError(dn.toString()));
const [error, mailbox] = await safe(mail.getMailbox(parts[0], parts[1]));
if (error) return next(new ldap.OperationsError(error.toString()));
if (!mailbox) return next(new ldap.NoSuchObjectError(req.dn.toString()));
if (!mailbox.active) return next(new ldap.NoSuchObjectError(req.dn.toString()));
if (!mailbox) return next(new ldap.NoSuchObjectError(dn.toString()));
if (!mailbox.active) return next(new ldap.NoSuchObjectError(dn.toString()));
const obj = {
dn: req.dn.toString(),
dn: dn.toString(),
attributes: {
objectclass: ['mailbox'],
objectcategory: 'mailbox',
cn: `${mailbox.name}@${mailbox.domain}`,
uid: `${mailbox.name}@${mailbox.domain}`,
mail: `${mailbox.name}@${mailbox.domain}`
mail: `${mailbox.name}@${mailbox.domain}`,
storagequota: mailbox.storageQuota,
messagesquota: mailbox.messagesQuota,
}
};
@@ -305,7 +309,7 @@ async function mailboxSearch(req, res, next) {
} else {
res.end();
}
} else { // new sogo
} else { // new sogo and dovecot listing (doveadm -A)
// TODO figure out how proper pagination here could work
let [error, mailboxes] = await safe(mail.listAllMailboxes(1, 100000));
if (error) return next(new ldap.OperationsError(error.toString()));
@@ -329,7 +333,9 @@ async function mailboxSearch(req, res, next) {
displayname: mailbox.ownerType === mail.OWNERTYPE_USER ? ownerObject.displayName : ownerObject.name,
cn: `${mailbox.name}@${mailbox.domain}`,
uid: `${mailbox.name}@${mailbox.domain}`,
mail: `${mailbox.name}@${mailbox.domain}`
mail: `${mailbox.name}@${mailbox.domain}`,
storagequota: mailbox.storageQuota,
messagesquota: mailbox.messagesQuota,
}
};
@@ -359,7 +365,7 @@ async function mailAliasSearch(req, res, next) {
const parts = email.split('@');
if (parts.length !== 2) return next(new ldap.NoSuchObjectError(req.dn.toString()));
const [error, alias] = await safe(mail.getAlias(parts[0], parts[1]));
const [error, alias] = await safe(mail.searchAlias(parts[0], parts[1]));
if (error) return next(new ldap.OperationsError(error.toString()));
if (!alias) return next(new ldap.NoSuchObjectError(req.dn.toString()));
@@ -373,7 +379,7 @@ async function mailAliasSearch(req, res, next) {
attributes: {
objectclass: ['nisMailAlias'],
objectcategory: 'nisMailAlias',
cn: `${alias.name}@${alias.domain}`,
cn: `${parts[0]}@${alias.domain}`, // alias.name can contain wildcard character
rfc822MailMember: `${alias.aliasName}@${alias.aliasDomain}`
}
};
@@ -449,7 +455,7 @@ async function authorizeUserForApp(req, res, next) {
// we return no such object, to avoid leakage of a users existence
if (!canAccess) return next(new ldap.NoSuchObjectError(req.dn.toString()));
await eventlog.upsertLoginEvent(eventlog.ACTION_USER_LOGIN, { authType: 'ldap', appId: req.app.id }, { userId: req.user.id, user: users.removePrivateFields(req.user) });
await eventlog.upsertLoginEvent(req.user.ghost ? eventlog.ACTION_USER_LOGIN_GHOST : eventlog.ACTION_USER_LOGIN, { authType: 'ldap', appId: req.app.id }, { userId: req.user.id, user: users.removePrivateFields(req.user) });
res.end();
}
@@ -594,7 +600,7 @@ async function authenticateService(serviceId, dn, req, res, next) {
if (verifyError && verifyError.reason === BoxError.INVALID_CREDENTIALS) return next(new ldap.InvalidCredentialsError(dn.toString()));
if (verifyError) return next(new ldap.OperationsError(verifyError.message));
eventlog.upsertLoginEvent(eventlog.ACTION_USER_LOGIN, { authType: 'ldap', mailboxId: email }, { userId: result.id, user: users.removePrivateFields(result) });
eventlog.upsertLoginEvent(result.ghost ? eventlog.ACTION_USER_LOGIN_GHOST : eventlog.ACTION_USER_LOGIN, { authType: 'ldap', mailboxId: email }, { userId: result.id, user: users.removePrivateFields(result) });
res.end();
}
+68 -26
View File
@@ -48,6 +48,7 @@ exports = module.exports = {
getAlias,
getAliases,
setAliases,
searchAlias,
getLists,
getList,
@@ -96,13 +97,11 @@ const assert = require('assert'),
services = require('./services.js'),
settings = require('./settings.js'),
shell = require('./shell.js'),
smtpTransport = require('nodemailer-smtp-transport'),
superagent = require('superagent'),
sysinfo = require('./sysinfo.js'),
system = require('./system.js'),
tasks = require('./tasks.js'),
users = require('./users.js'),
util = require('util'),
validator = require('validator'),
_ = require('underscore');
@@ -112,7 +111,7 @@ const REMOVE_MAILBOX_CMD = path.join(__dirname, 'scripts/rmmailbox.sh');
const OWNERTYPES = [ exports.OWNERTYPE_USER, exports.OWNERTYPE_GROUP, exports.OWNERTYPE_APP ];
// if you add a field here, listMailboxes has to be updated
const MAILBOX_FIELDS = [ 'name', 'type', 'ownerId', 'ownerType', 'aliasName', 'aliasDomain', 'creationTime', 'membersJson', 'membersOnly', 'domain', 'active', 'enablePop3' ].join(',');
const MAILBOX_FIELDS = [ 'name', 'type', 'ownerId', 'ownerType', 'aliasName', 'aliasDomain', 'creationTime', 'membersJson', 'membersOnly', 'domain', 'active', 'enablePop3', 'storageQuota', 'messagesQuota' ].join(',');
const MAILDB_FIELDS = [ 'domain', 'enabled', 'mailFromValidation', 'catchAllJson', 'relayJson', 'dkimKeyJson', 'dkimSelector', 'bannerJson' ].join(',');
function postProcessMailbox(data) {
@@ -169,6 +168,18 @@ function validateName(name) {
return null;
}
function validateAlias(name) {
assert.strictEqual(typeof name, 'string');
if (name.length < 1) return new BoxError(BoxError.BAD_FIELD, 'mailbox name must be atleast 1 char');
if (name.length >= 200) return new BoxError(BoxError.BAD_FIELD, 'mailbox name too long');
// also need to consider valid LDAP characters here (e.g '+' is reserved). keep hyphen at the end so it doesn't become a range.
if (/[^a-zA-Z0-9._*-]/.test(name)) return new BoxError(BoxError.BAD_FIELD, 'mailbox name can only contain alphanumerals, dot, hyphen, asterisk or underscore');
return null;
}
function validateDisplayName(name) {
assert.strictEqual(typeof name, 'string');
@@ -224,7 +235,8 @@ async function checkSmtpRelay(relay) {
connectionTimeout: 5000,
greetingTimeout: 5000,
host: relay.host,
port: relay.port
port: relay.port,
secure: false // haraka relay only supports STARTTLS
};
// only set auth if either username or password is provided, some relays auth based on IP (range)
@@ -237,9 +249,9 @@ async function checkSmtpRelay(relay) {
if (relay.acceptSelfSignedCerts) options.tls = { rejectUnauthorized: false };
const transporter = nodemailer.createTransport(smtpTransport(options));
const transporter = nodemailer.createTransport(options);
const [error] = await safe(util.promisify(transporter.verify)());
const [error] = await safe(transporter.verify());
result.status = !error;
if (error) {
result.value = result.errorMessage = error.message;
@@ -504,7 +516,11 @@ const RBL_LIST = [
// this function currently only looks for black lists based on IP. TODO: also look up by domain
async function checkRblStatus(domain) {
const ip = await sysinfo.getServerIPv4();
const [error, ip] = await safe(sysinfo.getServerIPv4());
if (error) {
debug(`checkRblStatus: unable to determine server IPv4: ${error.message}`);
return { status: false, ip: null, servers: [] };
}
const flippedIp = ip.split('.').reverse().join('.');
@@ -642,7 +658,7 @@ async function createMailConfig(mailFqdn) {
// create sections for per-domain configuration
for (const domain of mailDomains) {
const catchAll = domain.catchAll.map(function (c) { return `${c}@${domain.domain}`; }).join(',');
const catchAll = domain.catchAll.join(',');
const mailFromValidation = domain.mailFromValidation;
if (!safe.fs.appendFileSync(`${paths.MAIL_CONFIG_DIR}/mail.ini`,
@@ -698,15 +714,15 @@ async function configureMail(mailFqdn, mailDomain, serviceConfig) {
const memory = system.getMemoryAllocation(memoryLimit);
const cloudronToken = hat(8 * 128), relayToken = hat(8 * 128);
const bundle = await reverseProxy.getCertificatePath(mailFqdn, mailDomain);
const certificatePath = await reverseProxy.getCertificatePath(mailFqdn, mailDomain);
const dhparamsFilePath = `${paths.MAIL_CONFIG_DIR}/dhparams.pem`;
const mailCertFilePath = `${paths.MAIL_CONFIG_DIR}/tls_cert.pem`;
const mailKeyFilePath = `${paths.MAIL_CONFIG_DIR}/tls_key.pem`;
if (!safe.child_process.execSync(`cp ${paths.DHPARAMS_FILE} ${dhparamsFilePath}`)) throw new BoxError(BoxError.FS_ERROR, 'Could not copy dhparams:' + safe.error.message);
if (!safe.child_process.execSync(`cp ${bundle.certFilePath} ${mailCertFilePath}`)) throw new BoxError(BoxError.FS_ERROR, 'Could not create cert file:' + safe.error.message);
if (!safe.child_process.execSync(`cp ${bundle.keyFilePath} ${mailKeyFilePath}`)) throw new BoxError(BoxError.FS_ERROR, 'Could not create key file:' + safe.error.message);
if (!safe.child_process.execSync(`cp ${certificatePath.certFilePath} ${mailCertFilePath}`)) throw new BoxError(BoxError.FS_ERROR, 'Could not create cert file:' + safe.error.message);
if (!safe.child_process.execSync(`cp ${certificatePath.keyFilePath} ${mailKeyFilePath}`)) throw new BoxError(BoxError.FS_ERROR, 'Could not create key file:' + safe.error.message);
// if the 'yellowtent' user of OS and the 'cloudron' user of mail container don't match, the keys become inaccessible by mail code
if (!safe.fs.chmodSync(mailKeyFilePath, 0o644)) throw new BoxError(BoxError.FS_ERROR, `Could not chmod key file: ${safe.error.message}`);
@@ -1029,6 +1045,10 @@ async function setCatchAllAddress(domain, addresses) {
assert.strictEqual(typeof domain, 'string');
assert(Array.isArray(addresses));
for (const address of addresses) {
if (!validator.isEmail(address)) throw new BoxError(BoxError.BAD_FIELD, `Invalid catch all address: ${address}`);
}
await updateDomain(domain, { catchAll: addresses });
safe(restartMail(), { debug }); // have to restart mail container since haraka cannot watch symlinked config files (mail.ini)
@@ -1089,7 +1109,7 @@ async function listMailboxes(domain, search, page, perPage) {
const escapedSearch = mysql.escape('%' + search + '%'); // this also quotes the string
const searchQuery = search ? ` HAVING (name LIKE ${escapedSearch} OR aliasNames LIKE ${escapedSearch} OR aliasDomains LIKE ${escapedSearch})` : ''; // having instead of where because of aggregated columns use
const query = 'SELECT m1.name AS name, m1.domain AS domain, m1.ownerId AS ownerId, m1.ownerType as ownerType, m1.active as active, JSON_ARRAYAGG(m2.name) AS aliasNames, JSON_ARRAYAGG(m2.domain) AS aliasDomains, m1.enablePop3 AS enablePop3 '
const query = 'SELECT m1.name AS name, m1.domain AS domain, m1.ownerId AS ownerId, m1.ownerType as ownerType, m1.active as active, JSON_ARRAYAGG(m2.name) AS aliasNames, JSON_ARRAYAGG(m2.domain) AS aliasDomains, m1.enablePop3 AS enablePop3, m1.storageQuota AS storageQuota, m1.messagesQuota AS messagesQuota '
+ ` FROM (SELECT * FROM mailboxes WHERE type='${exports.TYPE_MAILBOX}') AS m1`
+ ` LEFT JOIN (SELECT * FROM mailboxes WHERE type='${exports.TYPE_ALIAS}') AS m2`
+ ' ON m1.name=m2.aliasName AND m1.domain=m2.aliasDomain AND m1.ownerId=m2.ownerId'
@@ -1110,7 +1130,7 @@ async function listAllMailboxes(page, perPage) {
assert.strictEqual(typeof page, 'number');
assert.strictEqual(typeof perPage, 'number');
const query = 'SELECT m1.name AS name, m1.domain AS domain, m1.ownerId AS ownerId, m1.ownerType as ownerType, m1.active as active, JSON_ARRAYAGG(m2.name) AS aliasNames, JSON_ARRAYAGG(m2.domain) AS aliasDomains, m1.enablePop3 AS enablePop3 '
const query = 'SELECT m1.name AS name, m1.domain AS domain, m1.ownerId AS ownerId, m1.ownerType as ownerType, m1.active as active, JSON_ARRAYAGG(m2.name) AS aliasNames, JSON_ARRAYAGG(m2.domain) AS aliasDomains, m1.enablePop3 AS enablePop3, m1.storageQuota AS storageQuota, m1.messagesQuota AS messagesQuota '
+ ` FROM (SELECT * FROM mailboxes WHERE type='${exports.TYPE_MAILBOX}') AS m1`
+ ` LEFT JOIN (SELECT * FROM mailboxes WHERE type='${exports.TYPE_ALIAS}') AS m2`
+ ' ON m1.name=m2.aliasName AND m1.domain=m2.aliasDomain AND m1.ownerId=m2.ownerId'
@@ -1164,10 +1184,12 @@ async function addMailbox(name, domain, data, auditSource) {
assert.strictEqual(typeof data, 'object');
assert.strictEqual(typeof auditSource, 'object');
const { ownerId, ownerType, active } = data;
const { ownerId, ownerType, active, storageQuota, messagesQuota } = data;
assert.strictEqual(typeof ownerId, 'string');
assert.strictEqual(typeof ownerType, 'string');
assert.strictEqual(typeof active, 'boolean');
assert(Number.isInteger(storageQuota) && storageQuota >= 0);
assert(Number.isInteger(messagesQuota) && messagesQuota >= 0);
name = name.toLowerCase();
@@ -1176,12 +1198,13 @@ async function addMailbox(name, domain, data, auditSource) {
if (!OWNERTYPES.includes(ownerType)) throw new BoxError(BoxError.BAD_FIELD, 'bad owner type');
[error] = await safe(database.query('INSERT INTO mailboxes (name, type, domain, ownerId, ownerType, active) VALUES (?, ?, ?, ?, ?, ?)', [ name, exports.TYPE_MAILBOX, domain, ownerId, ownerType, active ]));
[error] = await safe(database.query('INSERT INTO mailboxes (name, type, domain, ownerId, ownerType, active, storageQuota, messagesQuota) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
[ name, exports.TYPE_MAILBOX, domain, ownerId, ownerType, active, storageQuota, messagesQuota ]));
if (error && error.code === 'ER_DUP_ENTRY') throw new BoxError(BoxError.ALREADY_EXISTS, 'mailbox already exists');
if (error && error.code === 'ER_NO_REFERENCED_ROW_2' && error.sqlMessage.includes('mailboxes_domain_constraint')) throw new BoxError(BoxError.NOT_FOUND, `no such domain '${domain}'`);
if (error) throw error;
await eventlog.add(eventlog.ACTION_MAIL_MAILBOX_ADD, auditSource, { name, domain, ownerId, ownerType, active });
await eventlog.add(eventlog.ACTION_MAIL_MAILBOX_ADD, auditSource, { name, domain, ownerId, ownerType, active, storageQuota, messageQuota: messagesQuota });
}
async function updateMailbox(name, domain, data, auditSource) {
@@ -1190,23 +1213,30 @@ async function updateMailbox(name, domain, data, auditSource) {
assert.strictEqual(typeof data, 'object');
assert.strictEqual(typeof auditSource, 'object');
const { ownerId, ownerType, active, enablePop3 } = data;
assert.strictEqual(typeof ownerId, 'string');
assert.strictEqual(typeof ownerType, 'string');
assert.strictEqual(typeof active, 'boolean');
assert.strictEqual(typeof enablePop3, 'boolean');
const args = [];
const fields = [];
for (const k in data) {
if (k === 'enablePop3' || k === 'active') {
fields.push(k + ' = ?');
args.push(data[k] ? 1 : 0);
continue;
}
name = name.toLowerCase();
if (k === 'ownerType' && !OWNERTYPES.includes(data[k])) throw new BoxError(BoxError.BAD_FIELD, 'bad owner type');
if (!OWNERTYPES.includes(ownerType)) throw new BoxError(BoxError.BAD_FIELD, 'bad owner type');
fields.push(k + ' = ?');
args.push(data[k]);
}
args.push(name.toLowerCase());
args.push(domain);
const mailbox = await getMailbox(name, domain);
if (!mailbox) throw new BoxError(BoxError.NOT_FOUND, 'No such mailbox');
const result = await database.query('UPDATE mailboxes SET ownerId = ?, ownerType = ?, active = ?, enablePop3 = ? WHERE name = ? AND domain = ?', [ ownerId, ownerType, active, enablePop3, name, domain ]);
const result = await safe(database.query('UPDATE mailboxes SET ' + fields.join(', ') + ' WHERE name = ? AND domain = ?', args));
if (result.affectedRows === 0) throw new BoxError(BoxError.NOT_FOUND, 'Mailbox not found');
await eventlog.add(eventlog.ACTION_MAIL_MAILBOX_UPDATE, auditSource, { name, domain, oldUserId: mailbox.userId, ownerId, ownerType, active });
await eventlog.add(eventlog.ACTION_MAIL_MAILBOX_UPDATE, auditSource, Object.assign(data, { name, domain, oldUserId: mailbox.userId }) );
}
async function removeSolrIndex(mailbox) {
@@ -1258,6 +1288,18 @@ async function getAlias(name, domain) {
return results[0];
}
async function searchAlias(name, domain) {
assert.strictEqual(typeof name, 'string');
assert.strictEqual(typeof domain, 'string');
const results = await database.query(`SELECT ${MAILBOX_FIELDS} FROM mailboxes WHERE ? LIKE REPLACE(REPLACE(name, '*', '%'), '_', '\\_') AND type = ? AND domain = ?`, [ name, exports.TYPE_ALIAS, domain ]);
if (results.length === 0) return null;
results.forEach(function (result) { postProcessMailbox(result); });
return results[0];
}
async function getAliases(name, domain) {
assert.strictEqual(typeof name, 'string');
assert.strictEqual(typeof domain, 'string');
@@ -1277,7 +1319,7 @@ async function setAliases(name, domain, aliases, auditSource) {
const name = aliases[i].name.toLowerCase();
const domain = aliases[i].domain.toLowerCase();
const error = validateName(name);
const error = validateAlias(name);
if (error) throw error;
const mailDomain = await getDomain(domain);
+4 -3
View File
@@ -6,10 +6,11 @@
<p>{{ passwordResetEmail.description }}</p>
<p>
<a href="<%= resetLink %>">{{ passwordResetEmail.resetAction }}</a>
</p>
<br/>
<a style="border-radius: 2px; background-color: #2196f3; color: white; padding: 6px 12px; text-decoration: none;" href="<%= resetLink %>">{{ passwordResetEmail.resetAction }}</a>
<br/>
<br/>
{{ passwordResetEmail.expireNote }}
+3 -3
View File
@@ -5,9 +5,9 @@
<h3>{{ welcomeEmail.salutation }}</h3>
<h2>{{ welcomeEmail.welcomeTo }}</h2>
<p>
<a href="<%= inviteLink %>">{{ welcomeEmail.inviteLinkAction }}</a>
</p>
<br/>
<a style="border-radius: 2px; background-color: #2196f3; color: white; padding: 6px 12px; text-decoration: none;" href="<%= inviteLink %>">{{ welcomeEmail.inviteLinkAction }}</a>
<br/>
<br/>
+2 -3
View File
@@ -25,7 +25,6 @@ const assert = require('assert'),
safe = require('safetydance'),
settings = require('./settings.js'),
translation = require('./translation.js'),
smtpTransport = require('nodemailer-smtp-transport'),
util = require('util');
const MAIL_TEMPLATES_DIR = path.join(__dirname, 'mail_templates');
@@ -52,14 +51,14 @@ async function sendMail(mailOptions) {
const data = await mail.getMailAuth();
const transport = nodemailer.createTransport(smtpTransport({
const transport = nodemailer.createTransport({
host: data.ip,
port: data.port,
auth: {
user: mailOptions.authUser || `no-reply@${settings.dashboardDomain()}`,
pass: data.relayToken
}
}));
});
const transportSendMail = util.promisify(transport.sendMail.bind(transport));
const [error] = await safe(transportSendMail(mailOptions));
+1 -1
View File
@@ -184,7 +184,7 @@ async function getStatus(mountType, hostPath) {
if (end !== -1) message = lines.slice(start, end+1).map(line => line['MESSAGE']).join('\n');
}
if (!message) message = `Could not determine failure reason. ${safe.error ? safe.error.message : ''}`;
if (!message) message = `Could not determine mount failure reason. ${safe.error ? safe.error.message : ''}`;
} else {
message = 'Mounted';
}
+17 -3
View File
@@ -45,7 +45,7 @@ server {
location / {
<% if ( endpoint === 'dashboard' || endpoint === 'setup' ) { %>
return 301 https://$host$request_uri;
<% } else if ( endpoint === 'app' ) { %>
<% } else if ( endpoint === 'app' || endpoint === 'external' ) { %>
return 301 https://$host$request_uri;
<% } else if ( endpoint === 'redirect' ) { %>
return 301 https://<%= redirectTo %>$request_uri;
@@ -175,6 +175,12 @@ server {
proxy_pass http://127.0.0.1:3000;
<% } else if ( endpoint === 'app' ) { %>
proxy_pass http://<%= ip %>:<%= port %>;
<% } else if ( endpoint === 'external' ) { %>
# without a variable, nginx will not start if upstream is down or
resolver 127.0.0.1 valid=30s;
set $upstream <%= upstreamUri %>;
proxy_ssl_verify off;
proxy_pass $upstream;
<% } else if ( endpoint === 'redirect' ) { %>
return 302 https://<%= redirectTo %>$request_uri;
<% } %>
@@ -241,10 +247,10 @@ server {
client_max_body_size 0;
}
# graphite paths (uncomment block below and visit /graphite-web/dashboard)
# graphite paths (uncomment block below and visit /graphite-web/)
# remember to comment out the CSP policy as well to access the graphite dashboard
# location ~ ^/graphite-web/ {
# proxy_pass http://127.0.0.1:8417;
# proxy_pass http://172.18.0.6:8000;
# client_max_body_size 1m;
# }
@@ -326,6 +332,14 @@ server {
# to clear a permanent redirect on the browser
return 302 https://<%= redirectTo %>$request_uri;
}
<% } else if ( endpoint === 'external' ) { %>
location / {
# without a variable, nginx will not start if upstream is down or unavailable
resolver 127.0.0.1 valid=30s;
set $upstream <%= upstreamUri %>;
proxy_ssl_verify off;
proxy_pass $upstream;
}
<% } else if ( endpoint === 'ip' ) { %>
location /notfound.html {
root <%= sourceDir %>/dashboard/dist;
+5 -4
View File
@@ -14,6 +14,7 @@ exports = module.exports = {
ALERT_REBOOT: 'reboot',
ALERT_BOX_UPDATE: 'boxUpdate',
ALERT_UPDATE_UBUNTU: 'ubuntuUpdate',
ALERT_MANUAL_APP_UPDATE: 'manualAppUpdate',
alert,
@@ -189,16 +190,16 @@ async function boxUpdateError(eventId, errorMessage) {
await add(eventId, 'Cloudron update failed', `Failed to update Cloudron: ${errorMessage}.`);
}
async function certificateRenewalError(eventId, vhost, errorMessage) {
async function certificateRenewalError(eventId, fqdn, errorMessage) {
assert.strictEqual(typeof eventId, 'string');
assert.strictEqual(typeof vhost, 'string');
assert.strictEqual(typeof fqdn, 'string');
assert.strictEqual(typeof errorMessage, 'string');
await add(eventId, `Certificate renewal of ${vhost} failed`, `Failed to renew certs of ${vhost}: ${errorMessage}. Renewal will be retried in 12 hours.`);
await add(eventId, `Certificate renewal of ${fqdn} failed`, `Failed to renew certs of ${fqdn}: ${errorMessage}. Renewal will be retried in 12 hours.`);
const admins = await users.getAdmins();
for (const admin of admins) {
await mailer.certificateRenewalError(admin.email, vhost, errorMessage);
await mailer.certificateRenewalError(admin.email, fqdn, errorMessage);
}
}
+2 -1
View File
@@ -16,6 +16,7 @@ exports = module.exports = {
CLOUDRON_DEFAULT_AVATAR_FILE: path.join(__dirname + '/../assets/avatar.png'),
INFRA_VERSION_FILE: path.join(baseDir(), 'platformdata/INFRA_VERSION'),
CRON_SEED_FILE: path.join(baseDir(), 'platformdata/CRON_SEED'),
DASHBOARD_DIR: constants.TEST ? path.join(__dirname, '../../dashboard/src') : path.join(baseDir(), 'box/dashboard/dist'),
PROVIDER_FILE: '/etc/cloudron/PROVIDER',
@@ -30,7 +31,6 @@ exports = module.exports = {
ACME_CHALLENGES_DIR: path.join(baseDir(), 'platformdata/acme'),
ADDON_CONFIG_DIR: path.join(baseDir(), 'platformdata/addons'),
MAIL_CONFIG_DIR: path.join(baseDir(), 'platformdata/addons/mail'),
COLLECTD_APPCONFIG_DIR: path.join(baseDir(), 'platformdata/collectd/collectd.conf.d'),
LOGROTATE_CONFIG_DIR: path.join(baseDir(), 'platformdata/logrotate.d'),
NGINX_CONFIG_DIR: path.join(baseDir(), 'platformdata/nginx'),
NGINX_APPCONFIG_DIR: path.join(baseDir(), 'platformdata/nginx/applications'),
@@ -38,6 +38,7 @@ exports = module.exports = {
BACKUP_INFO_DIR: path.join(baseDir(), 'platformdata/backup'),
UPDATE_DIR: path.join(baseDir(), 'platformdata/update'),
UPDATE_CHECKER_FILE: path.join(baseDir(), 'platformdata/update/updatechecker.json'),
DISK_USAGE_FILE: path.join(baseDir(), 'platformdata/diskusage.json'),
SNAPSHOT_INFO_FILE: path.join(baseDir(), 'platformdata/backup/snapshot-info.json'),
DYNDNS_INFO_FILE: path.join(baseDir(), 'platformdata/dyndns-info.json'),
DHPARAMS_FILE: path.join(baseDir(), 'platformdata/dhparams.pem'),
+3 -3
View File
@@ -70,7 +70,7 @@ async function setupTask(domain, auditSource) {
assert.strictEqual(typeof auditSource, 'object');
try {
await cloudron.setupDnsAndCert(constants.DASHBOARD_LOCATION, domain, auditSource, (progress) => setProgress('setup', progress.message));
await cloudron.setupDnsAndCert(constants.DASHBOARD_SUBDOMAIN, domain, auditSource, (progress) => setProgress('setup', progress.message));
await ensureDhparams();
await cloudron.setDashboardDomain(domain, auditSource);
setProgress('setup', 'Done'),
@@ -111,7 +111,7 @@ async function setup(domainConfig, sysinfoConfig, auditSource) {
dkimSelector: 'cloudron'
};
await settings.setMailLocation(domain, `${constants.DASHBOARD_LOCATION}.${domain}`); // default mail location. do this before we add the domain for upserting mail DNS
await settings.setMailLocation(domain, `${constants.DASHBOARD_SUBDOMAIN}.${domain}`); // default mail location. do this before we add the domain for upserting mail DNS
await domains.add(domain, data, auditSource);
await settings.setSysinfoConfig(sysinfoConfig);
@@ -174,7 +174,7 @@ async function restoreTask(backupConfig, remotePath, sysinfoConfig, options, aud
await reverseProxy.restoreFallbackCertificates();
const dashboardDomain = settings.dashboardDomain(); // load this fresh from after the backup.restore
if (!options.skipDnsSetup) await cloudron.setupDnsAndCert(constants.DASHBOARD_LOCATION, dashboardDomain, auditSource, (progress) => setProgress('restore', progress.message));
if (!options.skipDnsSetup) await cloudron.setupDnsAndCert(constants.DASHBOARD_SUBDOMAIN, dashboardDomain, auditSource, (progress) => setProgress('restore', progress.message));
await cloudron.setDashboardDomain(dashboardDomain, auditSource);
await settings.setBackupCredentials(backupConfig); // update just the credentials and not the policy and flags
await eventlog.add(eventlog.ACTION_RESTORE, auditSource, { remotePath });
+14 -6
View File
@@ -50,15 +50,23 @@ function jwtVerify(req, res, next) {
});
}
async function basicAuthVerify(req, res, next) {
async function authorizationHeader(req, res, next) {
const appId = req.headers['x-app-id'] || '';
const credentials = basicAuth(req);
if (!appId || !credentials) return next();
if (!appId) return next();
if (!req.headers.authorization) return next();
const [error, app] = await safe(apps.get(appId));
if (error) return next(new HttpError(503, error.message));
if (!app) return next(new HttpError(503, 'Error getting app'));
if (!app.manifest.addons.proxyAuth.basicAuth) return next();
// only if the app supports bearer auth, pass it through to the app. without this flag, anyone can access the app with Bearer auth!
if (req.headers.authorization.startsWith('Bearer ') && app.manifest.addons.proxyAuth.supportsBearerAuth) return next(new HttpSuccess(200, {}));
const credentials = basicAuth(req);
if (!credentials) return next();
if (!app.manifest.addons.proxyAuth.basicAuth) return next(); // this is a flag because this allows auth to bypass 2FA
const verifyFunc = credentials.name.indexOf('@') !== -1 ? users.verifyWithEmail : users.verifyWithUsername;
const [verifyError, user] = await safe(verifyFunc(credentials.name, credentials.pass, appId));
@@ -139,7 +147,7 @@ function auth(req, res, next) {
res.set('x-remote-email', req.user.email);
res.set('x-remote-name', req.user.displayName);
return next(new HttpSuccess(200, {}));
next(new HttpSuccess(200, {}));
}
// endpoint called by login page, username and password posted as JSON body
@@ -243,7 +251,7 @@ function initializeAuthwallExpressSync() {
.use(middleware.lastMile());
router.get ('/login', loginPage);
router.get ('/auth', jwtVerify, basicAuthVerify, auth); // called by nginx before accessing protected page
router.get ('/auth', jwtVerify, authorizationHeader, auth); // called by nginx before accessing protected page
router.post('/login', json, passwordAuth, authorize);
router.get ('/logout', logoutPage);
router.post('/logout', json, logoutPage);
+132 -129
View File
@@ -1,26 +1,26 @@
'use strict';
exports = module.exports = {
setAppCertificate,
setFallbackCertificate,
setUserCertificate, // per location certificate
setFallbackCertificate, // per domain certificate
generateFallbackCertificate,
validateCertificate,
getCertificatePath,
getCertificatePath, // resolved cert path
ensureCertificate,
checkCerts,
// the 'configure' ensure a certificate and generate nginx config
// the 'configure' functions ensure a certificate and generate nginx config
configureApp,
unconfigureApp,
// these only generate nginx config
writeDefaultConfig,
writeDashboardConfig,
writeAppConfig,
writeAppConfigs,
removeAppConfigs,
restoreFallbackCertificates,
@@ -59,17 +59,14 @@ const RESTART_SERVICE_CMD = path.join(__dirname, 'scripts/restartservice.sh');
function nginxLocation(s) {
if (!s.startsWith('!')) return s;
let re = s.replace(/[\^$\\.*+?()[\]{}|]/g, '\\$&'); // https://github.com/es-shims/regexp.escape/blob/master/implementation.js
const re = s.replace(/[\^$\\.*+?()[\]{}|]/g, '\\$&'); // https://github.com/es-shims/regexp.escape/blob/master/implementation.js
return `~ ^(?!(${re.slice(1)}))`; // negative regex assertion - https://stackoverflow.com/questions/16302897/nginx-location-not-equal-to-regex
}
async function getAcmeApi(domainObject) {
assert.strictEqual(typeof domainObject, 'object');
const acmeApi = acme2;
let apiOptions = { prod: false, performHttpAuthorization: false, wildcard: false, email: '' };
const apiOptions = { prod: false, performHttpAuthorization: false, wildcard: false, email: '' };
apiOptions.prod = domainObject.tlsConfig.provider.match(/.*-prod/) !== null; // matches 'le-prod' or 'letsencrypt-prod'
apiOptions.performHttpAuthorization = domainObject.provider.match(/noop|manual|wildcard/) !== null;
apiOptions.wildcard = !!domainObject.tlsConfig.wildcard;
@@ -81,7 +78,7 @@ async function getAcmeApi(domainObject) {
const [error, owner] = await safe(users.getOwner());
apiOptions.email = (error || !owner) ? 'webmaster@cloudron.io' : owner.email; // can error if not activated yet
return { acmeApi, apiOptions };
return { acme2, apiOptions };
}
function getExpiryDate(certFilePath) {
@@ -144,19 +141,19 @@ function providerMatchesSync(domainObject, certFilePath, apiOptions) {
// note: https://tools.ietf.org/html/rfc4346#section-7.4.2 (certificate_list) requires that the
// servers certificate appears first (and not the intermediate cert)
function validateCertificate(location, domainObject, certificate) {
assert.strictEqual(typeof location, 'string');
function validateCertificate(subdomain, domainObject, certificate) {
assert.strictEqual(typeof subdomain, 'string');
assert.strictEqual(typeof domainObject, 'object');
assert(certificate && typeof certificate, 'object');
const cert = certificate.cert, key = certificate.key;
const { cert, key } = certificate;
// check for empty cert and key strings
if (!cert && key) return new BoxError(BoxError.BAD_FIELD, 'missing cert');
if (cert && !key) return new BoxError(BoxError.BAD_FIELD, 'missing key');
// -checkhost checks for SAN or CN exclusively. SAN takes precedence and if present, ignores the CN.
const fqdn = dns.fqdn(location, domainObject);
const fqdn = dns.fqdn(subdomain, domainObject);
let result = safe.child_process.execSync(`openssl x509 -noout -checkhost "${fqdn}"`, { encoding: 'utf8', input: cert });
if (result === null) return new BoxError(BoxError.BAD_FIELD, 'Unable to get certificate subject:' + safe.error.message);
@@ -198,7 +195,7 @@ async function generateFallbackCertificate(domain) {
let opensslConfWithSan;
const cn = domain;
debug(`generateFallbackCertificateSync: domain=${domain} cn=${cn}`);
debug(`generateFallbackCertificate: domain=${domain} cn=${cn}`);
opensslConfWithSan = `${opensslConf}\n[SAN]\nsubjectAltName=DNS:${domain},DNS:*.${cn}\n`;
const configFile = path.join(os.tmpdir(), 'openssl-' + crypto.randomBytes(4).readUInt32LE(0) + '.conf');
@@ -219,14 +216,13 @@ async function generateFallbackCertificate(domain) {
return { cert, key };
}
async function setFallbackCertificate(domain, fallback) {
async function setFallbackCertificate(domain, certificate) {
assert.strictEqual(typeof domain, 'string');
assert(fallback && typeof fallback === 'object');
assert.strictEqual(typeof fallback, 'object');
assert(certificate && typeof certificate === 'object');
debug(`setFallbackCertificate: setting certs for domain ${domain}`);
if (!safe.fs.writeFileSync(path.join(paths.NGINX_CERT_DIR, `${domain}.host.cert`), fallback.cert)) throw new BoxError(BoxError.FS_ERROR, safe.error.message);
if (!safe.fs.writeFileSync(path.join(paths.NGINX_CERT_DIR, `${domain}.host.key`), fallback.key)) throw new BoxError(BoxError.FS_ERROR, safe.error.message);
if (!safe.fs.writeFileSync(path.join(paths.NGINX_CERT_DIR, `${domain}.host.cert`), certificate.cert)) throw new BoxError(BoxError.FS_ERROR, safe.error.message);
if (!safe.fs.writeFileSync(path.join(paths.NGINX_CERT_DIR, `${domain}.host.key`), certificate.key)) throw new BoxError(BoxError.FS_ERROR, safe.error.message);
// TODO: maybe the cert is being used by the mail container
await reload();
@@ -250,55 +246,36 @@ function getFallbackCertificatePathSync(domain) {
return { certFilePath, keyFilePath };
}
function getAppCertificatePathSync(vhost) {
assert.strictEqual(typeof vhost, 'string');
function getUserCertificatePathSync(fqdn) {
assert.strictEqual(typeof fqdn, 'string');
const certFilePath = path.join(paths.NGINX_CERT_DIR, `${vhost}.user.cert`);
const keyFilePath = path.join(paths.NGINX_CERT_DIR, `${vhost}.user.key`);
const certFilePath = path.join(paths.NGINX_CERT_DIR, `${fqdn}.user.cert`);
const keyFilePath = path.join(paths.NGINX_CERT_DIR, `${fqdn}.user.key`);
return { certFilePath, keyFilePath };
}
function getAcmeCertificatePathSync(vhost, domainObject) {
assert.strictEqual(typeof vhost, 'string'); // this can contain wildcard domain (for alias domains)
function getAcmeCertificatePathSync(fqdn, domainObject) {
assert.strictEqual(typeof fqdn, 'string'); // this can contain wildcard domain (for alias domains)
assert.strictEqual(typeof domainObject, 'object');
let certName, certFilePath, keyFilePath, csrFilePath, acmeChallengesDir = paths.ACME_CHALLENGES_DIR;
if (vhost !== domainObject.domain && domainObject.tlsConfig.wildcard) { // bare domain is not part of wildcard SAN
certName = dns.makeWildcard(vhost).replace('*.', '_.');
if (fqdn !== domainObject.domain && domainObject.tlsConfig.wildcard) { // bare domain is not part of wildcard SAN
certName = dns.makeWildcard(fqdn).replace('*.', '_.');
certFilePath = path.join(paths.NGINX_CERT_DIR, `${certName}.cert`);
keyFilePath = path.join(paths.NGINX_CERT_DIR, `${certName}.key`);
csrFilePath = path.join(paths.NGINX_CERT_DIR, `${certName}.csr`);
} else {
certName = vhost;
certFilePath = path.join(paths.NGINX_CERT_DIR, `${vhost}.cert`);
keyFilePath = path.join(paths.NGINX_CERT_DIR, `${vhost}.key`);
csrFilePath = path.join(paths.NGINX_CERT_DIR, `${vhost}.csr`);
certName = fqdn;
certFilePath = path.join(paths.NGINX_CERT_DIR, `${fqdn}.cert`);
keyFilePath = path.join(paths.NGINX_CERT_DIR, `${fqdn}.key`);
csrFilePath = path.join(paths.NGINX_CERT_DIR, `${fqdn}.csr`);
}
return { certName, certFilePath, keyFilePath, csrFilePath, acmeChallengesDir };
}
async function setAppCertificate(location, domainObject, certificate) {
assert.strictEqual(typeof location, 'string');
assert.strictEqual(typeof domainObject, 'object');
assert.strictEqual(typeof certificate, 'object');
const fqdn = dns.fqdn(location, domainObject);
const { certFilePath, keyFilePath } = getAppCertificatePathSync(fqdn);
if (certificate.cert && certificate.key) {
if (!safe.fs.writeFileSync(certFilePath, certificate.cert)) throw safe.error;
if (!safe.fs.writeFileSync(keyFilePath, certificate.key)) throw safe.error;
} else { // remove existing cert/key
if (!safe.fs.unlinkSync(certFilePath)) debug(`Error removing cert: ${safe.error.message}`);
if (!safe.fs.unlinkSync(keyFilePath)) debug(`Error removing key: ${safe.error.message}`);
}
await reload();
}
async function getCertificatePath(fqdn, domain) {
assert.strictEqual(typeof fqdn, 'string');
assert.strictEqual(typeof domain, 'string');
@@ -309,38 +286,38 @@ async function getCertificatePath(fqdn, domain) {
const domainObject = await domains.get(domain);
const appCertPath = getAppCertificatePathSync(fqdn); // user cert always wins
if (fs.existsSync(appCertPath.certFilePath) && fs.existsSync(appCertPath.keyFilePath)) return appCertPath;
const userPath = getUserCertificatePathSync(fqdn); // user cert always wins
if (fs.existsSync(userPath.certFilePath) && fs.existsSync(userPath.keyFilePath)) return userPath;
if (domainObject.tlsConfig.provider === 'fallback') return getFallbackCertificatePathSync(domain);
const acmeCertPath = getAcmeCertificatePathSync(fqdn, domainObject);
if (fs.existsSync(acmeCertPath.certFilePath) && fs.existsSync(acmeCertPath.keyFilePath)) return acmeCertPath;
const acmePath = getAcmeCertificatePathSync(fqdn, domainObject);
if (fs.existsSync(acmePath.certFilePath) && fs.existsSync(acmePath.keyFilePath)) return acmePath;
return getFallbackCertificatePathSync(domain);
}
async function checkAppCertificate(vhost, domainObject) {
assert.strictEqual(typeof vhost, 'string'); // this can contain wildcard domain (for alias domains)
async function syncUserCertificate(fqdn, domainObject) {
assert.strictEqual(typeof fqdn, 'string'); // this can contain wildcard domain (for alias domains)
assert.strictEqual(typeof domainObject, 'object');
const subdomain = vhost.substr(0, vhost.length - domainObject.domain.length - 1);
const certificate = await apps.getCertificate(subdomain, domainObject.domain);
if (!certificate) return null;
const subdomain = fqdn.substr(0, fqdn.length - domainObject.domain.length - 1);
const userCertificate = await apps.getCertificate(subdomain, domainObject.domain);
if (!userCertificate) return null;
const { certFilePath, keyFilePath } = getAppCertificatePathSync(vhost);
const { certFilePath, keyFilePath } = getUserCertificatePathSync(fqdn);
if (!safe.fs.writeFileSync(certFilePath, certificate.cert)) throw new BoxError(BoxError.FS_ERROR, `Failed to write certificate: ${safe.error.message}`);
if (!safe.fs.writeFileSync(keyFilePath, certificate.key)) throw new BoxError(BoxError.FS_ERROR, `Failed to write key: ${safe.error.message}`);
if (!safe.fs.writeFileSync(certFilePath, userCertificate.cert)) throw new BoxError(BoxError.FS_ERROR, `Failed to write certificate: ${safe.error.message}`);
if (!safe.fs.writeFileSync(keyFilePath, userCertificate.key)) throw new BoxError(BoxError.FS_ERROR, `Failed to write key: ${safe.error.message}`);
return { certFilePath, keyFilePath };
}
async function checkAcmeCertificate(vhost, domainObject) {
assert.strictEqual(typeof vhost, 'string'); // this can contain wildcard domain (for alias domains)
async function syncAcmeCertificate(fqdn, domainObject) {
assert.strictEqual(typeof fqdn, 'string'); // this can contain wildcard domain (for alias domains)
assert.strictEqual(typeof domainObject, 'object');
const { certName, certFilePath, keyFilePath, csrFilePath } = getAcmeCertificatePathSync(vhost, domainObject);
const { certName, certFilePath, keyFilePath, csrFilePath } = getAcmeCertificatePathSync(fqdn, domainObject);
const privateKey = await blobs.get(`${blobs.CERT_PREFIX}-${certName}.key`);
const cert = await blobs.get(`${blobs.CERT_PREFIX}-${certName}.cert`);
@@ -356,11 +333,11 @@ async function checkAcmeCertificate(vhost, domainObject) {
return { certFilePath, keyFilePath };
}
async function updateCertBlobs(vhost, domainObject) {
assert.strictEqual(typeof vhost, 'string'); // this can contain wildcard domain (for alias domains)
async function updateCertBlobs(fqdn, domainObject) {
assert.strictEqual(typeof fqdn, 'string'); // this can contain wildcard domain (for alias domains)
assert.strictEqual(typeof domainObject, 'object');
const { certName, certFilePath, keyFilePath, csrFilePath } = getAcmeCertificatePathSync(vhost, domainObject);
const { certName, certFilePath, keyFilePath, csrFilePath } = getAcmeCertificatePathSync(fqdn, domainObject);
const privateKey = safe.fs.readFileSync(keyFilePath);
if (!privateKey) throw new BoxError(BoxError.FS_ERROR, `Failed to read private key: ${safe.error.message}`);
@@ -376,76 +353,76 @@ async function updateCertBlobs(vhost, domainObject) {
await blobs.set(`${blobs.CERT_PREFIX}-${certName}.csr`, csr);
}
async function ensureCertificate(vhost, domain, auditSource) {
assert.strictEqual(typeof vhost, 'string');
async function ensureCertificate(subdomain, domain, auditSource) {
assert.strictEqual(typeof subdomain, 'string');
assert.strictEqual(typeof domain, 'string');
assert.strictEqual(typeof auditSource, 'object');
const domainObject = await domains.get(domain);
let bundle = await checkAppCertificate(vhost, domainObject);
if (bundle) return { bundle, renewed: false };
const userCertificatePath = await syncUserCertificate(subdomain, domainObject);
if (userCertificatePath) return { certificatePath: userCertificatePath, renewed: false };
if (domainObject.tlsConfig.provider === 'fallback') {
debug(`ensureCertificate: ${vhost} will use fallback certs`);
debug(`ensureCertificate: ${subdomain} will use fallback certs`);
return { bundle: getFallbackCertificatePathSync(domain), renewed: false };
return { certificatePath: getFallbackCertificatePathSync(domain), renewed: false };
}
const { acmeApi, apiOptions } = await getAcmeApi(domainObject);
const { acme2, apiOptions } = await getAcmeApi(domainObject);
let notAfter = null;
const [, currentBundle] = await safe(checkAcmeCertificate(vhost, domainObject));
if (currentBundle) {
debug(`ensureCertificate: ${vhost} certificate already exists at ${currentBundle.keyFilePath}`);
notAfter = getExpiryDate(currentBundle.certFilePath);
const [, acmeCertificatePath] = await safe(syncAcmeCertificate(subdomain, domainObject));
if (acmeCertificatePath) {
debug(`ensureCertificate: ${subdomain} certificate already exists at ${acmeCertificatePath.keyFilePath}`);
notAfter = getExpiryDate(acmeCertificatePath.certFilePath);
const isExpiring = (notAfter - new Date()) <= (30 * 24 * 60 * 60 * 1000); // expiring in a month
if (!isExpiring && providerMatchesSync(domainObject, currentBundle.certFilePath, apiOptions)) return { bundle: currentBundle, renewed: false };
debug(`ensureCertificate: ${vhost} cert requires renewal`);
if (!isExpiring && providerMatchesSync(domainObject, acmeCertificatePath.certFilePath, apiOptions)) return { certificatePath: acmeCertificatePath, renewed: false };
debug(`ensureCertificate: ${subdomain} cert requires renewal`);
} else {
debug(`ensureCertificate: ${vhost} cert does not exist`);
debug(`ensureCertificate: ${subdomain} cert does not exist`);
}
debug('ensureCertificate: getting certificate for %s with options %j', vhost, apiOptions);
debug(`ensureCertificate: getting certificate for ${subdomain} with options ${JSON.stringify(apiOptions)}`);
const acmePaths = getAcmeCertificatePathSync(vhost, domainObject);
let [error] = await safe(acmeApi.getCertificate(vhost, domain, acmePaths, apiOptions));
const acmePaths = getAcmeCertificatePathSync(subdomain, domainObject);
const [error] = await safe(acme2.getCertificate(subdomain, domain, acmePaths, apiOptions));
debug(`ensureCertificate: error: ${error ? error.message : 'null'} cert: ${acmePaths.certFilePath || 'null'}`);
await safe(eventlog.add(currentBundle ? eventlog.ACTION_CERTIFICATE_RENEWAL : eventlog.ACTION_CERTIFICATE_NEW, auditSource, { domain: vhost, errorMessage: error ? error.message : '', notAfter }));
await safe(eventlog.add(acmeCertificatePath ? eventlog.ACTION_CERTIFICATE_RENEWAL : eventlog.ACTION_CERTIFICATE_NEW, auditSource, { domain: subdomain, errorMessage: error ? error.message : '', notAfter }));
if (error && currentBundle && (notAfter - new Date() > 0)) { // still some life left in this certificate
debug('ensureCertificate: continue using existing bundle since renewal failed');
return { bundle: currentBundle, renewed: false };
if (error && acmeCertificatePath && (notAfter - new Date() > 0)) { // still some life left in this certificate
debug('ensureCertificate: continue using existing certificate since renewal failed');
return { certificatePath: acmeCertificatePath, renewed: false };
}
if (!error) {
[error] = await safe(updateCertBlobs(vhost, domainObject));
if (!error) return { bundle: { certFilePath: acmePaths.certFilePath, keyFilePath: acmePaths.keyFilePath }, renewed: true };
const [updateCertError] = await safe(updateCertBlobs(subdomain, domainObject));
if (!updateCertError) return { certificatePath: { certFilePath: acmePaths.certFilePath, keyFilePath: acmePaths.keyFilePath }, renewed: true };
}
debug(`ensureCertificate: renewal of ${vhost} failed. using fallback certificates for ${domain}`);
debug(`ensureCertificate: renewal of ${subdomain} failed. using fallback certificates for ${domain}`);
return { bundle: getFallbackCertificatePathSync(domain), renewed: false };
return { certificatePath: getFallbackCertificatePathSync(domain), renewed: false };
}
async function writeDashboardNginxConfig(vhost, bundle) {
assert.strictEqual(typeof vhost, 'string');
assert.strictEqual(typeof bundle, 'object');
async function writeDashboardNginxConfig(fqdn, certificatePath) {
assert.strictEqual(typeof fqdn, 'string');
assert.strictEqual(typeof certificatePath, 'object');
const data = {
sourceDir: path.resolve(__dirname, '..'),
vhost: vhost,
vhost: fqdn,
hasIPv6: sysinfo.hasIPv6(),
endpoint: 'dashboard',
certFilePath: bundle.certFilePath,
keyFilePath: bundle.keyFilePath,
certFilePath: certificatePath.certFilePath,
keyFilePath: certificatePath.keyFilePath,
robotsTxtQuoted: JSON.stringify('User-agent: *\nDisallow: /\n'),
proxyAuth: { enabled: false, id: null, location: nginxLocation('/') },
ocsp: await isOcspEnabled(bundle.certFilePath)
ocsp: await isOcspEnabled(certificatePath.certFilePath)
};
const nginxConf = ejs.render(NGINX_APPCONFIG_EJS, data);
const nginxConfigFilename = path.join(paths.NGINX_APPCONFIG_DIR, `${vhost}.conf`);
const nginxConfigFilename = path.join(paths.NGINX_APPCONFIG_DIR, `${fqdn}.conf`);
if (!safe.fs.writeFileSync(nginxConfigFilename, nginxConf)) throw new BoxError(BoxError.FS_ERROR, safe.error);
@@ -457,10 +434,10 @@ async function writeDashboardConfig(domainObject) {
debug(`writeDashboardConfig: writing admin config for ${domainObject.domain}`);
const dashboardFqdn = dns.fqdn(constants.DASHBOARD_LOCATION, domainObject);
const bundle = await getCertificatePath(dashboardFqdn, domainObject.domain);
const dashboardFqdn = dns.fqdn(constants.DASHBOARD_SUBDOMAIN, domainObject);
const certificatePath = await getCertificatePath(dashboardFqdn, domainObject.domain);
await writeDashboardNginxConfig(dashboardFqdn, bundle);
await writeDashboardNginxConfig(dashboardFqdn, certificatePath);
}
function getNginxConfigFilename(app, fqdn, type) {
@@ -481,11 +458,11 @@ function getNginxConfigFilename(app, fqdn, type) {
return path.join(paths.NGINX_APPCONFIG_DIR, `${app.id}${nginxConfigFilenameSuffix}.conf`);
}
async function writeAppNginxConfig(app, fqdn, type, bundle) {
async function writeAppNginxConfig(app, fqdn, type, certificatePath) {
assert.strictEqual(typeof app, 'object');
assert.strictEqual(typeof fqdn, 'string');
assert.strictEqual(typeof type, 'string');
assert.strictEqual(typeof bundle, 'object');
assert.strictEqual(typeof certificatePath, 'object');
const data = {
sourceDir: path.resolve(__dirname, '..'),
@@ -495,17 +472,28 @@ async function writeAppNginxConfig(app, fqdn, type, bundle) {
port: null,
endpoint: null,
redirectTo: null,
certFilePath: bundle.certFilePath,
keyFilePath: bundle.keyFilePath,
certFilePath: certificatePath.certFilePath,
keyFilePath: certificatePath.keyFilePath,
robotsTxtQuoted: null,
cspQuoted: null,
hideHeaders: [],
proxyAuth: { enabled: false },
ocsp: await isOcspEnabled(bundle.certFilePath)
upstreamUri: '', // only for endpoint === external
ocsp: await isOcspEnabled(certificatePath.certFilePath)
};
if (type === apps.LOCATION_TYPE_PRIMARY || type === apps.LOCATION_TYPE_ALIAS || type === apps.LOCATION_TYPE_SECONDARY) {
data.endpoint = 'app';
if (app.manifest.id === constants.PROXY_APP_APPSTORE_ID) {
data.endpoint = 'external';
// prevent generating invalid nginx configs
if (!app.upstreamUri) throw new BoxError(BoxError.BAD_FIELD, 'upstreamUri cannot be empty');
data.upstreamUri = app.upstreamUri;
}
// maybe these should become per domain at some point
const reverseProxyConfig = app.reverseProxyConfig || {}; // some of our code uses fake app objects
if (reverseProxyConfig.robotsTxt) data.robotsTxtQuoted = JSON.stringify(app.reverseProxyConfig.robotsTxt);
@@ -544,20 +532,34 @@ async function writeAppNginxConfig(app, fqdn, type, bundle) {
await reload();
}
async function writeAppConfig(app) {
async function writeAppConfigs(app) {
assert.strictEqual(typeof app, 'object');
const appDomains = [{ domain: app.domain, fqdn: app.fqdn, type: apps.LOCATION_TYPE_PRIMARY }]
.concat(app.secondaryDomains.map(sd => { return { domain: sd.domain, fqdn: sd.fqdn, type: apps.LOCATION_TYPE_SECONDARY }; }))
.concat(app.redirectDomains.map(rd => { return { domain: rd.domain, fqdn: rd.fqdn, type: apps.LOCATION_TYPE_REDIRECT }; }))
.concat(app.aliasDomains.map(ad => { return { domain: ad.domain, fqdn: ad.fqdn, type: apps.LOCATION_TYPE_ALIAS }; }));
const appDomains = [{ domain: app.domain, fqdn: app.fqdn, certificate: app.certificate, type: apps.LOCATION_TYPE_PRIMARY }]
.concat(app.secondaryDomains.map(sd => { return { domain: sd.domain, certificate: sd.certificate, fqdn: sd.fqdn, type: apps.LOCATION_TYPE_SECONDARY }; }))
.concat(app.redirectDomains.map(rd => { return { domain: rd.domain, certificate: rd.certificate, fqdn: rd.fqdn, type: apps.LOCATION_TYPE_REDIRECT }; }))
.concat(app.aliasDomains.map(ad => { return { domain: ad.domain, certificate: ad.certificate, fqdn: ad.fqdn, type: apps.LOCATION_TYPE_ALIAS }; }));
for (const appDomain of appDomains) {
const bundle = await getCertificatePath(appDomain.fqdn, appDomain.domain);
await writeAppNginxConfig(app, appDomain.fqdn, appDomain.type, bundle);
const certificatePath = await getCertificatePath(appDomain.fqdn, appDomain.domain);
await writeAppNginxConfig(app, appDomain.fqdn, appDomain.type, certificatePath);
}
}
async function setUserCertificate(app, fqdn, certificate) {
const { certFilePath, keyFilePath } = getUserCertificatePathSync(fqdn);
if (certificate !== null) {
if (!safe.fs.writeFileSync(certFilePath, certificate.cert)) throw safe.error;
if (!safe.fs.writeFileSync(keyFilePath, certificate.key)) throw safe.error;
} else { // remove existing cert/key
if (!safe.fs.unlinkSync(certFilePath)) debug(`Error removing cert: ${safe.error.message}`);
if (!safe.fs.unlinkSync(keyFilePath)) debug(`Error removing key: ${safe.error.message}`);
}
await writeAppConfigs(app);
}
async function configureApp(app, auditSource) {
assert.strictEqual(typeof app, 'object');
assert.strictEqual(typeof auditSource, 'object');
@@ -571,7 +573,7 @@ async function configureApp(app, auditSource) {
await ensureCertificate(appDomain.fqdn, appDomain.domain, auditSource);
}
await writeAppConfig(app);
await writeAppConfigs(app);
}
async function unconfigureApp(app) {
@@ -623,7 +625,7 @@ async function renewCerts(options, auditSource, progressCallback) {
progressCallback({ percent: progress, message: `Ensuring certs of ${appDomain.fqdn}` });
progress += Math.round(100/appDomains.length);
const { bundle, renewed } = await ensureCertificate(appDomain.fqdn, appDomain.domain, auditSource);
const { certificatePath, renewed } = await ensureCertificate(appDomain.fqdn, appDomain.domain, auditSource);
if (renewed) renewedCerts.push(appDomain.fqdn);
@@ -631,15 +633,15 @@ async function renewCerts(options, auditSource, progressCallback) {
// hack to check if the app's cert changed or not. this doesn't handle prod/staging le change since they use same file name
let currentNginxConfig = safe.fs.readFileSync(appDomain.nginxConfigFilename, 'utf8') || '';
if (currentNginxConfig.includes(bundle.certFilePath)) continue;
if (currentNginxConfig.includes(certificatePath.certFilePath)) continue;
debug(`renewCerts: creating new nginx config since ${appDomain.nginxConfigFilename} does not have ${bundle.certFilePath}`);
debug(`renewCerts: creating new nginx config since ${appDomain.nginxConfigFilename} does not have ${certificatePath.certFilePath}`);
// reconfigure since the cert changed
if (appDomain.type === 'webadmin' || appDomain.type === 'webadmin+mail') {
await writeDashboardNginxConfig(settings.dashboardFqdn(), bundle);
await writeDashboardNginxConfig(settings.dashboardFqdn(), certificatePath);
} else {
await writeAppNginxConfig(appDomain.app, appDomain.fqdn, appDomain.type, bundle);
await writeAppNginxConfig(appDomain.app, appDomain.fqdn, appDomain.type, certificatePath);
}
}
@@ -657,14 +659,15 @@ async function renewCerts(options, auditSource, progressCallback) {
}
}
async function cleanupCerts(auditSource) {
async function cleanupCerts(auditSource, progressCallback) {
assert.strictEqual(typeof auditSource, 'object');
assert.strictEqual(typeof progressCallback, 'function');
const filenames = await fs.promises.readdir(paths.NGINX_CERT_DIR);
const certFilenames = filenames.filter(f => f.endsWith('.cert'));
const now = new Date();
debug('cleanupCerts: start');
progressCallback({ message: 'Checking expired certs for removal' });
const fqdns = [];
@@ -675,7 +678,7 @@ async function cleanupCerts(auditSource) {
if (now - notAfter >= (60 * 60 * 24 * 30 * 6 * 1000)) { // expired 6 months ago
const fqdn = certFilename.replace(/\.cert$/, '');
debug(`cleanupCerts: deleting certs of ${fqdn}`);
progressCallback({ message: `deleting certs of ${fqdn}` });
// it is safe to delete the certs of stopped apps because their nginx configs are removed
safe.fs.unlinkSync(certFilePath);
@@ -701,7 +704,7 @@ async function checkCerts(options, auditSource, progressCallback) {
assert.strictEqual(typeof progressCallback, 'function');
await renewCerts(options, auditSource, progressCallback);
await cleanupCerts(auditSource);
await cleanupCerts(auditSource, progressCallback);
}
function removeAppConfigs() {
@@ -710,7 +713,7 @@ function removeAppConfigs() {
debug('removeAppConfigs: reomving nginx configs of apps');
// remove all configs which are not the default or current dashboard
for (let appConfigFile of fs.readdirSync(paths.NGINX_APPCONFIG_DIR)) {
for (const appConfigFile of fs.readdirSync(paths.NGINX_APPCONFIG_DIR)) {
if (appConfigFile !== constants.NGINX_DEFAULT_CONFIG_FILE_NAME && appConfigFile !== dashboardConfigFilename) {
fs.unlinkSync(path.join(paths.NGINX_APPCONFIG_DIR, appConfigFile));
}
+27 -13
View File
@@ -8,8 +8,8 @@ exports = module.exports = {
authorizeOperator,
};
const accesscontrol = require('../accesscontrol.js'),
apps = require('../apps.js'),
const apps = require('../apps.js'),
tokens = require('../tokens.js'),
assert = require('assert'),
BoxError = require('../boxerror.js'),
externalLdap = require('../externalldap.js'),
@@ -43,8 +43,13 @@ async function passwordAuth(req, res, next) {
if (!user.ghost && !user.appPassword && user.twoFactorAuthenticationEnabled) {
if (!totpToken) return next(new HttpError(401, 'A totpToken must be provided'));
const verified = speakeasy.totp.verify({ secret: user.twoFactorAuthenticationSecret, encoding: 'base32', token: totpToken, window: 2 });
if (!verified) return next(new HttpError(401, 'Invalid totpToken'));
if (user.source === 'ldap') {
const [error] = await safe(externalLdap.verifyPasswordAndTotpToken(user, password, totpToken));
if (error) return next(new HttpError(401, 'Invalid totpToken'));
} else {
const verified = speakeasy.totp.verify({ secret: user.twoFactorAuthenticationSecret, encoding: 'base32', token: totpToken, window: 2 });
if (!verified) return next(new HttpError(401, 'Invalid totpToken'));
}
}
req.user = user;
@@ -53,27 +58,32 @@ async function passwordAuth(req, res, next) {
}
async function tokenAuth(req, res, next) {
let token;
let accessToken;
// this determines the priority
if (req.body && req.body.access_token) token = req.body.access_token;
if (req.query && req.query.access_token) token = req.query.access_token;
if (req.body && req.body.access_token) accessToken = req.body.access_token;
if (req.query && req.query.access_token) accessToken = req.query.access_token;
if (req.headers && req.headers.authorization) {
const parts = req.headers.authorization.split(' ');
if (parts.length == 2) {
const [scheme, credentials] = parts;
if (/^Bearer$/i.test(scheme)) token = credentials;
if (/^Bearer$/i.test(scheme)) accessToken = credentials;
}
}
if (!token) return next(new HttpError(401, 'Token required'));
if (!accessToken) return next(new HttpError(401, 'Token required'));
const [error, user] = await safe(accesscontrol.verifyToken(token));
if (error && error.reason === BoxError.INVALID_CREDENTIALS) return next(new HttpError(401, error.message));
if (error) return next(new HttpError(500, error.message));
const token = await tokens.getByAccessToken(accessToken);
if (!token) return next(new HttpError(401, 'No such token'));
req.access_token = token; // used in logout route
const user = await users.get(token.identifier);
if (!user) return next(new HttpError(401,'User not found'));
if (!user.active) return next(new HttpError(401,'User not active'));
await safe(tokens.update(token.id, { lastUsedTime: new Date() })); // ignore any error
req.token = token;
req.user = user;
next();
@@ -84,8 +94,10 @@ function authorize(requiredRole) {
return function (req, res, next) {
assert.strictEqual(typeof req.user, 'object');
assert.strictEqual(typeof req.token, 'object');
if (users.compareRoles(req.user.role, requiredRole) < 0) return next(new HttpError(403, `role '${requiredRole}' is required but user has only '${req.user.role}'`));
if (!tokens.hasScope(req.token, req.method, req.path)) return next(new HttpError(403, 'access token does not have this scope'));
next();
};
@@ -95,7 +107,9 @@ async function authorizeOperator(req, res, next) {
assert.strictEqual(typeof req.params.id, 'string');
assert.strictEqual(typeof req.user, 'object');
assert.strictEqual(typeof req.app, 'object');
assert.strictEqual(typeof req.token, 'object');
if (!tokens.hasScope(req.token, req.method, req.path)) return next(new HttpError(403, 'access token does not have this scope'));
if (apps.isOperator(req.app, req.user)) return next();
return next(new HttpError(403, 'user is not an operator'));
+91
View File
@@ -0,0 +1,91 @@
'use strict';
exports = module.exports = {
listByUser,
add,
get,
update,
remove,
getIcon
};
const assert = require('assert'),
applinks = require('../applinks.js'),
BoxError = require('../boxerror.js'),
safe = require('safetydance'),
HttpError = require('connect-lastmile').HttpError,
HttpSuccess = require('connect-lastmile').HttpSuccess;
async function listByUser(req, res, next) {
assert.strictEqual(typeof req.user, 'object');
const [error, result] = await safe(applinks.listByUser(req.user));
if (error) return next(BoxError.toHttpError(error));
// we have a separate route for this
result.forEach(function (a) { delete a.icon; });
next(new HttpSuccess(200, { applinks: result }));
}
async function add(req, res, next) {
assert.strictEqual(typeof req.body, 'object');
if (!req.body.upstreamUri || typeof req.body.upstreamUri !== 'string') return next(new HttpError(400, 'upstreamUri must be a non-empty string'));
if ('label' in req.body && typeof req.body.label !== 'string') return next(new HttpError(400, 'label must be a string'));
if ('tags' in req.body && !Array.isArray(req.body.tags)) return next(new HttpError(400, 'tags must be an array with strings'));
if ('accessRestriction' in req.body && typeof req.body.accessRestriction !== 'object') return next(new HttpError(400, 'accessRestriction must be an object'));
const [error] = await safe(applinks.add(req.body));
if (error) return next(BoxError.toHttpError(error));
next(new HttpSuccess(201, {}));
}
async function get(req, res, next) {
assert.strictEqual(typeof req.params.id, 'string');
const [error, result] = await safe(applinks.get(req.params.id));
if (error) return next(BoxError.toHttpError(error));
if (!result) return next(new HttpError(404, 'Applink not found'));
// we have a separate route for this
delete result.icon;
next(new HttpSuccess(200, result));
}
async function update(req, res, next) {
assert.strictEqual(typeof req.params.id, 'string');
assert.strictEqual(typeof req.body, 'object');
if (!req.body.upstreamUri || typeof req.body.upstreamUri !== 'string') return next(new HttpError(400, 'upstreamUri must be a non-empty string'));
if ('label' in req.body && typeof req.body.label !== 'string') return next(new HttpError(400, 'label must be a string'));
if ('tags' in req.body && !Array.isArray(req.body.tags)) return next(new HttpError(400, 'tags must be an array with strings'));
if ('accessRestriction' in req.body && typeof req.body.accessRestriction !== 'object') return next(new HttpError(400, 'accessRestriction must be an object'));
if ('icon' in req.body && typeof req.body.icon !== 'string') return next(new HttpError(400, 'icon must be a string'));
const [error] = await safe(applinks.update(req.params.id, req.body));
if (error) return next(BoxError.toHttpError(error));
next(new HttpSuccess(202, {}));
}
async function remove(req, res, next) {
assert.strictEqual(typeof req.params.id, 'string');
const [error] = await safe(applinks.remove(req.params.id));
if (error) return next(BoxError.toHttpError(error));
next(new HttpSuccess(204));
}
async function getIcon(req, res, next) {
assert.strictEqual(typeof req.params.id, 'string');
const [error, icon] = await safe(applinks.getIcon(req.params.id, { original: req.query.original }));
if (error) return next(BoxError.toHttpError(error));
if (!icon) return next(new HttpError(404, 'no such icon'));
res.send(icon);
}
+36 -3
View File
@@ -37,6 +37,7 @@ exports = module.exports = {
setLocation,
setStorage,
setMounts,
setUpstreamUri,
stop,
start,
@@ -57,6 +58,7 @@ exports = module.exports = {
updateBackup,
getLimits,
getGraphs,
load
};
@@ -65,7 +67,9 @@ const apps = require('../apps.js'),
assert = require('assert'),
AuditSource = require('../auditsource.js'),
BoxError = require('../boxerror.js'),
constants = require('../constants.js'),
debug = require('debug')('box:routes/apps'),
graphs = require('../graphs.js'),
HttpError = require('connect-lastmile').HttpError,
HttpSuccess = require('connect-lastmile').HttpSuccess,
safe = require('safetydance'),
@@ -171,9 +175,13 @@ async function install(req, res, next) {
if ('skipDnsSetup' in data && typeof data.skipDnsSetup !== 'boolean') return next(new HttpError(400, 'skipDnsSetup must be boolean'));
if ('enableMailbox' in data && typeof data.enableMailbox !== 'boolean') return next(new HttpError(400, 'enableMailbox must be boolean'));
if ('upstreamUri' in data && (typeof data.upstreamUri !== 'string' || !data.upstreamUri)) return next(new HttpError(400, 'upstreamUri must be a non emptry string'));
let [error, result] = await safe(apps.downloadManifest(data.appStoreId, data.manifest));
if (error) return next(BoxError.toHttpError(error));
if (result.manifest.appStoreId === constants.PROXY_APP_APPSTORE_ID && (typeof data.upstreamUri !== 'string' || !data.upstreamUri)) return next(new HttpError(400, 'upstreamUri must be a non empty string'));
if (safe.query(result.manifest, 'addons.docker') && req.user.role !== users.ROLE_OWNER) return next(new HttpError(403, '"owner" role is required to install app with docker addon'));
data.appStoreId = result.appStoreId;
@@ -403,7 +411,6 @@ async function setLocation(req, res, next) {
assert.strictEqual(typeof req.app, 'object');
if (typeof req.body.subdomain !== 'string') return next(new HttpError(400, 'subdomain must be string')); // subdomain may be an empty string
if (!req.body.domain) return next(new HttpError(400, 'domain is required'));
if (typeof req.body.domain !== 'string') return next(new HttpError(400, 'domain must be string'));
if ('portBindings' in req.body && typeof req.body.portBindings !== 'object') return next(new HttpError(400, 'portBindings must be an object'));
@@ -492,16 +499,17 @@ async function importApp(req, res, next) {
const data = req.body;
if ('remotePath' in data) { // if not provided, we import in-place
if (typeof data.remotePath !== 'string') return next(new HttpError(400, 'remotePath must be string'));
if (typeof data.remotePath !== 'string' || !data.remotePath) return next(new HttpError(400, 'remotePath must be non-empty string'));
if (typeof data.backupFormat !== 'string') return next(new HttpError(400, 'backupFormat must be string'));
if ('backupConfig' in data && typeof data.backupConfig !== 'object') return next(new HttpError(400, 'backupConfig must be an object'));
const backupConfig = req.body.backupConfig;
if (req.body.backupConfig) {
if (backupConfig) {
if (typeof backupConfig.provider !== 'string') return next(new HttpError(400, 'provider is required'));
if ('password' in backupConfig && typeof backupConfig.password !== 'string') return next(new HttpError(400, 'password must be a string'));
if ('encryptedFilenames' in backupConfig && typeof backupConfig.encryptedFilenames !== 'boolean') return next(new HttpError(400, 'encryptedFilenames must be a boolean'));
if ('acceptSelfSignedCerts' in backupConfig && typeof backupConfig.acceptSelfSignedCerts !== 'boolean') return next(new HttpError(400, 'format must be a boolean'));
// testing backup config can take sometime
@@ -898,6 +906,18 @@ async function setMounts(req, res, next) {
next(new HttpSuccess(202, { taskId: result.taskId }));
}
async function setUpstreamUri(req, res, next) {
assert.strictEqual(typeof req.body, 'object');
assert.strictEqual(typeof req.app, 'object');
if (typeof req.body.upstreamUri !== 'string') return next(new HttpError(400, 'upstreamUri must be a string'));
const [error] = await safe(apps.setUpstreamUri(req.app, req.body.upstreamUri, AuditSource.fromRequest(req)));
if (error) return next(BoxError.toHttpError(error));
next(new HttpSuccess(200, {}));
}
async function listEventlog(req, res, next) {
assert.strictEqual(typeof req.app, 'object');
@@ -941,3 +961,16 @@ async function getLimits(req, res, next) {
next(new HttpSuccess(200, { limits }));
}
async function getGraphs(req, res, next) {
assert.strictEqual(typeof req.app, 'object');
if (!req.query.fromMinutes || !parseInt(req.query.fromMinutes)) return next(new HttpError(400, 'fromMinutes must be a number'));
const fromMinutes = parseInt(req.query.fromMinutes);
const noNullPoints = !!req.query.noNullPoints;
const [error, result] = await safe(graphs.getContainerStats(req.app.id, fromMinutes, noNullPoints));
if (error) return next(new HttpError(500, error));
next(new HttpSuccess(200, result));
}
+34 -5
View File
@@ -10,6 +10,8 @@ exports = module.exports = {
isRebootRequired,
getConfig,
getDisks,
getDiskUsage,
updateDiskUsage,
getMemory,
getUpdateInfo,
update,
@@ -23,7 +25,8 @@ exports = module.exports = {
getServerIpv6,
getLanguages,
syncExternalLdap,
syncDnsRecords
syncDnsRecords,
getSystemGraphs
};
const assert = require('assert'),
@@ -34,6 +37,7 @@ const assert = require('assert'),
debug = require('debug')('box:routes/cloudron'),
eventlog = require('../eventlog.js'),
externalLdap = require('../externalldap.js'),
graphs = require('../graphs.js'),
HttpError = require('connect-lastmile').HttpError,
HttpSuccess = require('connect-lastmile').HttpSuccess,
safe = require('safetydance'),
@@ -63,7 +67,7 @@ async function login(req, res, next) {
[error, token] = await safe(tokens.add({ clientId: type, identifier: req.user.id, expires: Date.now() + constants.DEFAULT_TOKEN_EXPIRATION_MSECS }));
if (error) return next(new HttpError(500, error));
await eventlog.add(eventlog.ACTION_USER_LOGIN, auditSource, { userId: req.user.id, user: users.removePrivateFields(req.user) });
await eventlog.add(req.user.ghost ? eventlog.ACTION_USER_LOGIN_GHOST : eventlog.ACTION_USER_LOGIN, auditSource, { userId: req.user.id, user: users.removePrivateFields(req.user) });
if (!req.user.ghost) safe(users.notifyLoginLocation(req.user, ip, userAgent, auditSource), { debug });
@@ -71,11 +75,11 @@ async function login(req, res, next) {
}
async function logout(req, res) {
assert.strictEqual(typeof req.access_token, 'string');
assert.strictEqual(typeof req.token, 'object');
await eventlog.add(eventlog.ACTION_USER_LOGOUT, AuditSource.fromRequest(req), { userId: req.user.id, user: users.removePrivateFields(req.user) });
await safe(tokens.delByAccessToken(req.access_token));
await safe(tokens.delByAccessToken(req.token.accessToken));
res.redirect('/login.html');
}
@@ -166,7 +170,21 @@ async function getDisks(req, res, next) {
const [error, result] = await safe(system.getDisks());
if (error) return next(BoxError.toHttpError(error));
next(new HttpSuccess(200, result));
next(new HttpSuccess(200, { disks: result }));
}
async function getDiskUsage(req, res, next) {
const [error, result] = await safe(system.getDiskUsage());
if (error) return next(BoxError.toHttpError(error));
next(new HttpSuccess(200, { usage: result }));
}
async function updateDiskUsage(req, res, next) {
const [error, taskId] = await safe(cloudron.updateDiskUsage());
if (error) return next(BoxError.toHttpError(error));
next(new HttpSuccess(201, { taskId }));
}
async function getMemory(req, res, next) {
@@ -327,3 +345,14 @@ async function syncDnsRecords(req, res, next) {
next(new HttpSuccess(201, { taskId }));
}
async function getSystemGraphs(req, res, next) {
if (!req.query.fromMinutes || !parseInt(req.query.fromMinutes)) return next(new HttpError(400, 'fromMinutes must be a number'));
const fromMinutes = parseInt(req.query.fromMinutes);
const noNullPoints = !!req.query.noNullPoints;
const [error, result] = await safe(graphs.getSystem(fromMinutes, noNullPoints));
if (error) return next(new HttpError(500, error));
next(new HttpSuccess(200, result));
}
-38
View File
@@ -1,38 +0,0 @@
'use strict';
exports = module.exports = {
getGraphs
};
const middleware = require('../middleware/index.js'),
HttpError = require('connect-lastmile').HttpError,
url = require('url');
// for testing locally: curl 'http://127.0.0.1:8417/graphite-web/render?format=json&from=-1min&target=absolute(collectd.localhost.du-docker.capacity-usage)'
// the datapoint is (value, timestamp) https://buildmedia.readthedocs.org/media/pdf/graphite/0.9.16/graphite.pdf
const graphiteProxy = middleware.proxy(url.parse('http://127.0.0.1:8417'));
function getGraphs(req, res, next) {
const parsedUrl = url.parse(req.url, true /* parseQueryString */);
delete parsedUrl.query['access_token'];
delete req.headers['authorization'];
delete req.headers['cookies'];
// 'graphite-web' is the URL_PREFIX in docker-graphite
req.url = url.format({ pathname: 'graphite-web/render', query: parsedUrl.query });
// graphs may take very long to respond so we run into headers already sent issues quite often
// nginx still has a request timeout which can deal with this then.
req.clearTimeout();
graphiteProxy(req, res, function (error) {
if (!error) return next();
if (error.code === 'ECONNREFUSED') return next(new HttpError(424, 'Unable to connect to graphite'));
// ECONNRESET here is most likely because of a bug in the query or the uwsgi buffer size is too small
if (error.code === 'ECONNRESET') return next(new HttpError(424, 'Unable to query graphite'));
next(new HttpError(500, error));
});
}
+2 -2
View File
@@ -6,7 +6,7 @@ exports = module.exports = {
add,
update,
remove,
updateMembers
setMembers
};
const assert = require('assert'),
@@ -49,7 +49,7 @@ async function update(req, res, next) {
next(new HttpSuccess(200, { }));
}
async function updateMembers(req, res, next) {
async function setMembers(req, res, next) {
assert.strictEqual(typeof req.params.groupId, 'string');
if (!req.body.userIds) return next(new HttpError(404, 'missing or invalid userIds fields'));
+1 -1
View File
@@ -4,6 +4,7 @@ exports = module.exports = {
accesscontrol: require('./accesscontrol.js'),
appPasswords: require('./apppasswords.js'),
apps: require('./apps.js'),
applinks: require('./applinks.js'),
appstore: require('./appstore.js'),
backups: require('./backups.js'),
branding: require('./branding.js'),
@@ -11,7 +12,6 @@ exports = module.exports = {
domains: require('./domains.js'),
eventlog: require('./eventlog.js'),
filemanager: require('./filemanager.js'),
graphs: require('./graphs.js'),
groups: require('./groups.js'),
mail: require('./mail.js'),
mailserver: require('./mailserver.js'),
+10
View File
@@ -177,6 +177,11 @@ async function addMailbox(req, res, next) {
if (typeof req.body.ownerType !== 'string') return next(new HttpError(400, 'ownerType must be a string'));
if (typeof req.body.active !== 'boolean') return next(new HttpError(400, 'active must be a boolean'));
if (!Number.isInteger(req.body.storageQuota)) return next(new HttpError(400, 'storageQuota must be an integer'));
if (req.body.storageQuota < 0) return next(new HttpError(400, 'storageQuota must be a postive integer or zero'));
if (!Number.isInteger(req.body.messagesQuota)) return next(new HttpError(400, 'messagesQuota must be an integer'));
if (req.body.messagesQuota < 0) return next(new HttpError(400, 'messagesQuota must be a positive integer or zero'));
const [error] = await safe(mail.addMailbox(req.body.name, req.params.domain, req.body, AuditSource.fromRequest(req)));
if (error) return next(BoxError.toHttpError(error));
@@ -192,6 +197,11 @@ async function updateMailbox(req, res, next) {
if (typeof req.body.active !== 'boolean') return next(new HttpError(400, 'active must be a boolean'));
if (typeof req.body.enablePop3 !== 'boolean') return next(new HttpError(400, 'enablePop3 must be a boolean'));
if (!Number.isInteger(req.body.storageQuota)) return next(new HttpError(400, 'storageQuota must be an integer'));
if (req.body.storageQuota < 0) return next(new HttpError(400, 'storageQuota must be a postive integer or zero'));
if (!Number.isInteger(req.body.messagesQuota)) return next(new HttpError(400, 'messagesQuota must be an integer'));
if (req.body.messagesQuota < 0) return next(new HttpError(400, 'messagesQuota must be a positive integer or zero'));
const [error] = await safe(mail.updateMailbox(req.params.name, req.params.domain, req.body, AuditSource.fromRequest(req)));
if (error) return next(BoxError.toHttpError(error));
+15 -5
View File
@@ -3,6 +3,7 @@
exports = module.exports = {
proxy,
restart,
queueProxy,
setLocation,
getLocation
@@ -26,9 +27,8 @@ async function restart(req, res, next) {
next();
}
async function proxy(req, res, next) {
let parsedUrl = url.parse(req.url, true /* parseQueryString */);
const pathname = req.path.split('/').pop();
async function proxyToMailContainer(port, pathname, req, res, next) {
const parsedUrl = url.parse(req.url, true /* parseQueryString */);
// do not proxy protected values
delete parsedUrl.query['access_token'];
@@ -39,9 +39,9 @@ async function proxy(req, res, next) {
if (error) return next(BoxError.toHttpError(error));
parsedUrl.query['access_token'] = addonDetails.token;
req.url = url.format({ pathname: pathname, query: parsedUrl.query });
req.url = url.format({ pathname, query: parsedUrl.query });
const proxyOptions = url.parse(`http://${addonDetails.ip}:3000`);
const proxyOptions = url.parse(`http://${addonDetails.ip}:${port}`);
const mailserverProxy = middleware.proxy(proxyOptions);
req.clearTimeout(); // TODO: add timeout to mail server proxy logic instead of this
@@ -55,6 +55,16 @@ async function proxy(req, res, next) {
});
}
async function proxy(req, res, next) {
const pathname = req.path.split('/').pop();
proxyToMailContainer(3000, pathname, req, res, next);
}
async function queueProxy(req, res, next) {
proxyToMailContainer(6000, req.path.replace('/', '/queue/'), req, res, next);
}
async function getLocation(req, res, next) {
const [error, result] = await safe(mail.getLocation());
if (error) return next(BoxError.toHttpError(error));
+1 -1
View File
@@ -52,7 +52,7 @@ async function update(req, res, next) {
assert.strictEqual(typeof req.notification, 'object');
assert.strictEqual(typeof req.body, 'object');
if (typeof req.body.acknowledged !== 'boolean') return next(new HttpError(400, 'acknowledged must be a booliean'));
if (typeof req.body.acknowledged !== 'boolean') return next(new HttpError(400, 'acknowledged must be a boolean'));
const [error] = await safe(notifications.update(req.notification, { acknowledged: req.body.acknowledged }));
if (error) return next(BoxError.toHttpError(error));
+2
View File
@@ -103,6 +103,8 @@ async function restore(req, res, next) {
const backupConfig = req.body.backupConfig;
if (typeof backupConfig.provider !== 'string') return next(new HttpError(400, 'provider is required'));
if ('password' in backupConfig && typeof backupConfig.password !== 'string') return next(new HttpError(400, 'password must be a string'));
if ('encryptedFilenames' in req.body && typeof req.body.encryptedFilenames !== 'boolean') return next(new HttpError(400, 'encryptedFilenames must be a boolean'));
if (typeof backupConfig.format !== 'string') return next(new HttpError(400, 'format must be a string'));
if ('acceptSelfSignedCerts' in backupConfig && typeof backupConfig.acceptSelfSignedCerts !== 'boolean') return next(new HttpError(400, 'format must be a boolean'));
+16 -1
View File
@@ -7,12 +7,14 @@ exports = module.exports = {
getLogs,
getLogStream,
restart,
rebuild
rebuild,
getGraphs
};
const assert = require('assert'),
AuditSource = require('../auditsource.js'),
BoxError = require('../boxerror.js'),
graphs = require('../graphs.js'),
HttpError = require('connect-lastmile').HttpError,
HttpSuccess = require('connect-lastmile').HttpSuccess,
safe = require('safetydance'),
@@ -131,3 +133,16 @@ async function rebuild(req, res, next) {
next(new HttpSuccess(202, {}));
}
async function getGraphs(req, res, next) {
assert.strictEqual(typeof req.params.service, 'string');
if (!req.query.fromMinutes || !parseInt(req.query.fromMinutes)) return next(new HttpError(400, 'fromMinutes must be a number'));
const fromMinutes = parseInt(req.query.fromMinutes);
const noNullPoints = !!req.query.noNullPoints;
const [error, result] = await safe(graphs.getContainerStats(req.params.service, fromMinutes, noNullPoints));
if (error) return next(new HttpError(500, error));
next(new HttpSuccess(200, result));
}
+8 -6
View File
@@ -74,6 +74,8 @@ async function setBackupConfig(req, res, next) {
if (typeof req.body.provider !== 'string') return next(new HttpError(400, 'provider is required'));
if (typeof req.body.schedulePattern !== 'string') return next(new HttpError(400, 'schedulePattern is required'));
if ('password' in req.body && typeof req.body.password !== 'string') return next(new HttpError(400, 'password must be a string'));
if ('encryptedFilenames' in req.body && typeof req.body.encryptedFilenames !== 'boolean') return next(new HttpError(400, 'encryptedFilenames must be a boolean'));
if ('syncConcurrency' in req.body) {
if (typeof req.body.syncConcurrency !== 'number') return next(new HttpError(400, 'syncConcurrency must be a positive integer'));
if (req.body.syncConcurrency < 1) return next(new HttpError(400, 'syncConcurrency must be a positive integer'));
@@ -137,21 +139,21 @@ async function setExternalLdapConfig(req, res, next) {
next(new HttpSuccess(200, {}));
}
async function getUserDirectoryConfig(req, res, next) {
const [error, config] = await safe(settings.getUserDirectoryConfig());
async function getDirectoryServerConfig(req, res, next) {
const [error, config] = await safe(settings.getDirectoryServerConfig());
if (error) return next(BoxError.toHttpError(error));
next(new HttpSuccess(200, config));
}
async function setUserDirectoryConfig(req, res, next) {
async function setDirectoryServerConfig(req, res, next) {
assert.strictEqual(typeof req.body, 'object');
if (typeof req.body.enabled !== 'boolean') return next(new HttpError(400, 'enabled must be a boolean'));
if (typeof req.body.secret !== 'string') return next(new HttpError(400, 'secret must be a string'));
if ('allowlist' in req.body && typeof req.body.allowlist !== 'string') return next(new HttpError(400, 'allowlist must be a string'));
const [error] = await safe(settings.setUserDirectoryConfig(req.body));
const [error] = await safe(settings.setDirectoryServerConfig(req.body));
if (error) return next(BoxError.toHttpError(error));
next(new HttpSuccess(200, {}));
@@ -298,7 +300,7 @@ function get(req, res, next) {
case settings.IPV6_CONFIG_KEY: return getIPv6Config(req, res, next);
case settings.BACKUP_CONFIG_KEY: return getBackupConfig(req, res, next);
case settings.EXTERNAL_LDAP_KEY: return getExternalLdapConfig(req, res, next);
case settings.USER_DIRECTORY_KEY: return getUserDirectoryConfig(req, res, next);
case settings.DIRECTORY_SERVER_KEY: return getDirectoryServerConfig(req, res, next);
case settings.UNSTABLE_APPS_KEY: return getUnstableAppsConfig(req, res, next);
case settings.REGISTRY_CONFIG_KEY: return getRegistryConfig(req, res, next);
case settings.SYSINFO_CONFIG_KEY: return getSysinfoConfig(req, res, next);
@@ -321,7 +323,7 @@ function set(req, res, next) {
case settings.DYNAMIC_DNS_KEY: return setDynamicDnsConfig(req, res, next);
case settings.IPV6_CONFIG_KEY: return setIPv6Config(req, res, next);
case settings.EXTERNAL_LDAP_KEY: return setExternalLdapConfig(req, res, next);
case settings.USER_DIRECTORY_KEY: return setUserDirectoryConfig(req, res, next);
case settings.DIRECTORY_SERVER_KEY: return setDirectoryServerConfig(req, res, next);
case settings.UNSTABLE_APPS_KEY: return setUnstableAppsConfig(req, res, next);
case settings.REGISTRY_CONFIG_KEY: return setRegistryConfig(req, res, next);
case settings.SYSINFO_CONFIG_KEY: return setSysinfoConfig(req, res, next);
-3
View File
@@ -63,9 +63,6 @@ async function canEnableRemoteSupport(req, res, next) {
const sshdConfig = safe.fs.readFileSync(SSHD_CONFIG_FILE, 'utf8');
if (!sshdConfig) return next(new HttpError(412, `Failed to read file ${SSHD_CONFIG_FILE}`));
// only check for PermitRootLogin if we want to enable remote support
if (req.body.enable && !sshdConfig.split('\n').find(function (line) { return line.search(/^PermitRootLogin.*yes/) !== -1; })) return next(new HttpError(417, `Set "PermitRootLogin yes" in ${SSHD_CONFIG_FILE}`));
next();
}
+2 -2
View File
@@ -333,10 +333,10 @@ xdescribe('App API', function () {
it('app install fails - reserved smtp subdomain', function (done) {
superagent.post(SERVER_URL + '/api/v1/apps/install')
.query({ access_token: token })
.send({ manifest: APP_MANIFEST, subdomain: constants.SMTP_LOCATION, accessRestriction: null, domain: DOMAIN_0.domain })
.send({ manifest: APP_MANIFEST, subdomain: constants.SMTP_SUBDOMAIN, accessRestriction: null, domain: DOMAIN_0.domain })
.end(function (err, res) {
expect(res.statusCode).to.equal(400);
expect(res.body.message).to.contain(constants.SMTP_LOCATION + ' is reserved');
expect(res.body.message).to.contain(constants.SMTP_SUBDOMAIN + ' is reserved');
done();
});
});
+2 -20
View File
@@ -29,13 +29,13 @@ describe('Appstore Apps API', function () {
it('cannot get app with bad token', async function () {
const scope1 = nock(settings.apiServerOrigin())
.get(`/api/v1/apps/org.wordpress.cloudronapp?accessToken=${appstoreToken}`)
.reply(402, {});
.reply(403, {});
const response = await superagent.get(`${serverUrl}/api/v1/appstore/apps/org.wordpress.cloudronapp`)
.query({ access_token: owner.token })
.ok(() => true);
expect(response.statusCode).to.be(402);
expect(response.statusCode).to.be(412);
expect(scope1.isDone()).to.be.ok();
});
@@ -109,15 +109,6 @@ describe('Appstore Cloudron Registration API - existing user', function () {
nock.cleanAll();
});
it('cannot re-register - already registered', async function () {
const response = await superagent.post(`${serverUrl}/api/v1/appstore/register_cloudron`)
.send({ email: 'test@cloudron.io', password: 'secret', signup: false })
.query({ access_token: owner.token })
.ok(() => true);
expect(response.statusCode).to.equal(409);
});
it('can get subscription', async function () {
const scope1 = nock(settings.apiServerOrigin())
.get('/api/v1/subscription?accessToken=CLOUDRON_TOKEN', () => true)
@@ -165,15 +156,6 @@ describe('Appstore Cloudron Registration API - new user signup', function () {
expect(await settings.getAppstoreWebToken()).to.be('SECRET_TOKEN');
});
it('cannot re-register - already registered', async function () {
const response = await superagent.post(`${serverUrl}/api/v1/appstore/register_cloudron`)
.send({ email: 'test@cloudron.io', password: 'secret', signup: false })
.query({ access_token: owner.token })
.ok(() => true);
expect(response.statusCode).to.equal(409);
});
it('can get subscription', async function () {
const scope1 = nock(settings.apiServerOrigin())
.get('/api/v1/subscription?accessToken=CLOUDRON_TOKEN', () => true)
+55 -1
View File
@@ -10,11 +10,13 @@ const constants = require('../../constants.js'),
expect = require('expect.js'),
http = require('http'),
os = require('os'),
paths = require('../../paths.js'),
safe = require('safetydance'),
superagent = require('superagent'),
settings = require('../../settings.js');
describe('Cloudron API', function () {
const { setup, cleanup, serverUrl, owner, user } = common;
const { setup, cleanup, serverUrl, owner, user, waitForTask } = common;
before(setup);
after(cleanup);
@@ -369,6 +371,58 @@ describe('Cloudron API', function () {
});
});
describe('disks', function () {
it('succeeds', async function () {
const response = await superagent.get(`${serverUrl}/api/v1/cloudron/disks`)
.query({ access_token: owner.token });
expect(response.statusCode).to.equal(200);
expect(response.body.disks).to.be.ok();
expect(Object.keys(response.body.disks).some(fs => response.body.disks[fs].mountpoint === '/')).to.be(true);
});
});
describe('disk usage', function () {
it('get succeeds with no cache', async function () {
safe.fs.unlinkSync(paths.DISK_USAGE_FILE);
const response = await superagent.get(`${serverUrl}/api/v1/cloudron/disk_usage`)
.query({ access_token: owner.token })
.send({});
expect(response.statusCode).to.equal(200);
expect(response.body).to.eql({ usage: null });
});
it('update the cache', async function () {
const response = await superagent.post(`${serverUrl}/api/v1/cloudron/disk_usage`)
.query({ access_token: owner.token });
expect(response.statusCode).to.equal(201);
expect(response.body.taskId).to.be.ok();
await waitForTask(response.body.taskId);
});
it('get succeeds with cache', async function () {
const response = await superagent.get(`${serverUrl}/api/v1/cloudron/disk_usage`)
.query({ access_token: owner.token })
.send({});
expect(response.statusCode).to.equal(200);
expect(response.body.usage.ts).to.be.a('number');
const filesystems = Object.keys(response.body.usage.disks);
let dockerUsage = null;
for (const fs of filesystems) {
for (const content of response.body.usage.disks[fs].contents) {
if (content.id === 'docker') dockerUsage = content;
}
}
expect(dockerUsage).to.be.ok();
expect(dockerUsage.usage).to.be.a('number');
});
});
describe('languages', function () {
it('succeeds', async function () {
const response = await superagent.get(`${serverUrl}/api/v1/cloudron/languages`);
+4 -1
View File
@@ -107,7 +107,10 @@ async function waitForTask(taskId) {
for (let i = 0; i < 10; i++) {
const result = await tasks.get(taskId);
expect(result).to.not.be(null);
if (!result.active) return;
if (!result.active) {
if (result.success) return result;
throw new Error(`Task ${taskId} failed: ${result.error.message} - ${result.error.stack}`);
}
await delay(2000);
console.log(`Waiting for task to ${taskId} finish`);
}
+20 -7
View File
@@ -352,10 +352,19 @@ describe('Mail API', function () {
expect(response.statusCode).to.equal(400);
});
it('cannot set with bad addresses field', async function () {
const response = await superagent.post(`${serverUrl}/api/v1/mail/${dashboardDomain}/catch_all`)
.query({ access_token: owner.token })
.send({ addresses: [ 'user1' ] })
.ok(() => true);
expect(response.statusCode).to.equal(400);
});
it('set succeeds', async function () {
const response = await superagent.post(`${serverUrl}/api/v1/mail/${dashboardDomain}/catch_all`)
.query({ access_token: owner.token })
.send({ addresses: [ 'user1' ] });
.send({ addresses: [ `user1@${dashboardDomain}` ] });
expect(response.statusCode).to.equal(202);
});
@@ -365,7 +374,7 @@ describe('Mail API', function () {
.query({ access_token: owner.token });
expect(response.statusCode).to.equal(200);
expect(response.body.catchAll).to.eql([ 'user1' ]);
expect(response.body.catchAll).to.eql([ `user1@${dashboardDomain}` ]);
});
});
@@ -422,7 +431,7 @@ describe('Mail API', function () {
it('add succeeds', async function () {
const response = await superagent.post(`${serverUrl}/api/v1/mail/${dashboardDomain}/mailboxes`)
.send({ name: MAILBOX_NAME, ownerId: owner.id, ownerType: 'user', active: true })
.send({ name: MAILBOX_NAME, ownerId: owner.id, ownerType: 'user', active: true, storageQuota: 10, messagesQuota: 20 })
.query({ access_token: owner.token });
expect(response.statusCode).to.equal(201);
@@ -430,7 +439,7 @@ describe('Mail API', function () {
it('cannot add again', async function () {
const response = await superagent.post(`${serverUrl}/api/v1/mail/${dashboardDomain}/mailboxes`)
.send({ name: MAILBOX_NAME, ownerId: owner.id, ownerType: 'user', active: true })
.send({ name: MAILBOX_NAME, ownerId: owner.id, ownerType: 'user', active: true, storageQuota: 10, messagesQuota: 20 })
.query({ access_token: owner.token })
.ok(() => true);
@@ -457,6 +466,8 @@ describe('Mail API', function () {
expect(response.body.mailbox.aliasName).to.equal(null);
expect(response.body.mailbox.aliasDomain).to.equal(null);
expect(response.body.mailbox.domain).to.equal(dashboardDomain);
expect(response.body.mailbox.storageQuota).to.equal(10);
expect(response.body.mailbox.messagesQuota).to.equal(20);
});
it('listing succeeds', async function () {
@@ -471,6 +482,8 @@ describe('Mail API', function () {
expect(response.body.mailboxes[0].ownerType).to.equal('user');
expect(response.body.mailboxes[0].aliases).to.eql([]);
expect(response.body.mailboxes[0].domain).to.equal(dashboardDomain);
expect(response.body.mailboxes[0].storageQuota).to.equal(10);
expect(response.body.mailboxes[0].messagesQuota).to.equal(20);
});
it('disable fails even if not exist', async function () {
@@ -505,7 +518,7 @@ describe('Mail API', function () {
it('add the mailbox', async function () {
const response = await superagent.post(`${serverUrl}/api/v1/mail/${dashboardDomain}/mailboxes`)
.send({ name: MAILBOX_NAME, ownerId: owner.id, ownerType: 'user', active: true })
.send({ name: MAILBOX_NAME, ownerId: owner.id, ownerType: 'user', active: true, storageQuota: 10, messagesQuota: 20 })
.query({ access_token: owner.token });
expect(response.statusCode).to.equal(201);
@@ -539,7 +552,7 @@ describe('Mail API', function () {
it('set succeeds', async function () {
const response = await superagent.put(`${serverUrl}/api/v1/mail/${dashboardDomain}/mailboxes/${MAILBOX_NAME}/aliases`)
.send({ aliases: [{ name: 'hello', domain: dashboardDomain}, {name: 'there', domain: dashboardDomain}] })
.send({ aliases: [{ name: 'hello*', domain: dashboardDomain}, {name: 'there', domain: dashboardDomain}] })
.query({ access_token: owner.token });
expect(response.statusCode).to.equal(202);
@@ -550,7 +563,7 @@ describe('Mail API', function () {
.query({ access_token: owner.token });
expect(response.statusCode).to.equal(200);
expect(response.body.aliases).to.eql([{ name: 'hello', domain: dashboardDomain}, {name: 'there', domain: dashboardDomain}]);
expect(response.body.aliases).to.eql([{ name: 'hello*', domain: dashboardDomain}, {name: 'there', domain: dashboardDomain}]);
});
it('get fails if mailbox does not exist', async function () {
+31 -2
View File
@@ -15,7 +15,7 @@ describe('Tokens API', function () {
before(setup);
after(cleanup);
let token;
let token, readOnlyToken;
it('cannot create token with bad name', async function () {
const response = await superagent.post(`${serverUrl}/api/v1/tokens`)
@@ -35,13 +35,42 @@ describe('Tokens API', function () {
token = response.body;
});
it('can create read-only token', async function () {
const response = await superagent.post(`${serverUrl}/api/v1/tokens`)
.query({ access_token: owner.token })
.send({ name: 'mytoken1', scope: { '*': 'r' }});
expect(response.status).to.equal(201);
expect(response.body).to.be.a('object');
readOnlyToken = response.body;
});
it('cannot create read-only token with invalid scope', async function () {
const response = await superagent.post(`${serverUrl}/api/v1/tokens`)
.query({ access_token: owner.token })
.send({ name: 'mytoken1', scope: { 'foobar': 'rw' }})
.ok(() => true);
expect(response.status).to.equal(400);
});
it('can list tokens', async function () {
const response = await superagent.get(`${serverUrl}/api/v1/tokens`)
.query({ access_token: owner.token });
expect(response.statusCode).to.equal(200);
expect(response.body.tokens.length).to.be(2); // one is owner token on activation
expect(response.body.tokens.length).to.be(3); // one is owner token on activation
const tokenIds = response.body.tokens.map(t => t.id);
expect(tokenIds).to.contain(token.id);
expect(tokenIds).to.contain(readOnlyToken.id);
});
it('cannot create token with read only token', async function () {
const response = await superagent.post(`${serverUrl}/api/v1/tokens`)
.query({ access_token: readOnlyToken.accessToken })
.send({ name: 'somename' })
.ok(() => true);
expect(response.status).to.equal(403);
});
it('cannot get non-existent token', async function () {
+1 -1
View File
@@ -591,7 +591,7 @@ describe('Users API', function () {
it('add mailbox succeeds as mail manager', async function () {
const response = await superagent.post(`${serverUrl}/api/v1/mail/${dashboardDomain}/mailboxes`)
.send({ name: 'support', ownerId: owner.id, ownerType: 'user', active: true })
.send({ name: 'support', ownerId: owner.id, ownerType: 'user', active: true, storageQuota: 0, messagesQuota: 0 })
.query({ access_token: user.token });
expect(response.statusCode).to.equal(201);
+3 -1
View File
@@ -50,10 +50,12 @@ async function add(req, res, next) {
if (typeof req.body.name !== 'string') return next(new HttpError(400, 'name must be string'));
if ('expiresAt' in req.body && typeof req.body.expiresAt !== 'number') return next(new HttpError(400, 'expiresAt must be number'));
if ('scope' in req.body && typeof req.body.scope !== 'object') return next(new HttpError(400, 'scope must be an object'));
const expiresAt = req.body.expiresAt || (Date.now() + (100 * 365 * 24 * 60 * 60 * 1000)); // forever - 100 years TODO maybe we should allow 0 or -1 to make that explicit
const scope = req.body.scope || null;
const [error, result] = await safe(tokens.add({ clientId: tokens.ID_SDK, identifier: req.user.id, expires: expiresAt, name: req.body.name }));
const [error, result] = await safe(tokens.add({ clientId: tokens.ID_SDK, identifier: req.user.id, expires: expiresAt, name: req.body.name, scope }));
if (error) return next(BoxError.toHttpError(error));
next(new HttpSuccess(201, result));
+3 -3
View File
@@ -56,8 +56,8 @@ function dumpMemoryInfo() {
return (bytes / Math.pow(1024, i)).toFixed(2) * 1 + '' + sizes[i];
}
debug(`process: rss: ${h(mu.rss)} heapUsed: ${h(mu.heapUsed)} heapTotal: ${h(mu.heapTotal)} external: ${h(mu.external)}`);
debug(`v8 heap: used ${h(hs.used_heap_size)} total: ${h(hs.total_heap_size)} max: ${h(hs.heap_size_limit)}`);
debug(`process: rss=${h(mu.rss)} heapUsed=${h(mu.heapUsed)} heapTotal=${h(mu.heapTotal)} external=${h(mu.external)}`
+ ` v8 heap: used=${h(hs.used_heap_size)} total=${h(hs.total_heap_size)} max=${h(hs.heap_size_limit)}`);
}
(async function main() {
@@ -65,7 +65,7 @@ function dumpMemoryInfo() {
await settings.initCache();
dumpMemoryInfo();
const timerId = setInterval(dumpMemoryInfo, 30000);
const timerId = setInterval(dumpMemoryInfo, 180 * 1000);
const [uploadError] = await safe(backuptask.upload(remotePath, format, dataLayoutString, throttledProgressCallback(5000)));
debug('upload completed. error: ', uploadError);
-44
View File
@@ -1,44 +0,0 @@
#!/bin/bash
set -eu -o pipefail
if [[ ${EUID} -ne 0 ]]; then
echo "This script should be run as root." > /dev/stderr
exit 1
fi
if [[ $# == 1 && "$1" == "--check" ]]; then
echo "OK"
exit 0
fi
cmd="$1"
metric="$2" # note that this can also be 'cloudron-backup' or appid
if [[ "${BOX_ENV}" == "cloudron" ]]; then
# when restoring the cloudron with many apps, the apptasks rush in to restart
# collectd which makes systemd/collectd very unhappy and puts the collectd in
# inactive state
for i in {1..10}; do
echo "Restarting collectd"
if systemctl restart collectd; then
break
fi
echo "Failed to reload collectd. Maybe some other apptask is restarting it"
sleep $((RANDOM%30))
done
# delete old stats when uninstalling an app
if [[ "${cmd}" == "remove" ]]; then
echo "Removing collectd stats of ${metric}"
for i in {1..10}; do
if rm -rf ${HOME}/platformdata/graphite/whisper/collectd/localhost/*${metric}*; then
break
fi
echo "Failed to remove collectd directory. collectd possibly generated data in the middle of removal"
sleep 3
done
fi
fi
+23
View File
@@ -0,0 +1,23 @@
#!/bin/bash
set -eu -o pipefail
if [[ ${EUID} -ne 0 ]]; then
echo "This script should be run as root." > /dev/stderr
exit 1
fi
if [[ $# -eq 0 ]]; then
echo "No arguments supplied"
exit 1
fi
if [[ "$1" == "--check" ]]; then
echo "OK"
exit 0
fi
path="$1"
# -B1 makes du print block sizes and not apparent sizes (to match df which also uses block sizes)
du -DsB1 "${path}"
+61 -44
View File
@@ -79,14 +79,17 @@ function initializeExpressSync() {
const multipart = middleware.multipart({ maxFieldsSize: FIELD_LIMIT, limit: FILE_SIZE_LIMIT, timeout: FILE_TIMEOUT });
// to keep routes code short
// authentication
const password = routes.accesscontrol.passwordAuth;
const token = routes.accesscontrol.tokenAuth;
// authorization
const authorizeOwner = routes.accesscontrol.authorize(users.ROLE_OWNER);
const authorizeAdmin = routes.accesscontrol.authorize(users.ROLE_ADMIN);
const authorizeOperator = routes.accesscontrol.authorizeOperator;
const authorizeUserManager = routes.accesscontrol.authorize(users.ROLE_USER_MANAGER);
const authorizeMailManager = routes.accesscontrol.authorize(users.ROLE_MAIL_MANAGER);
const authorizeUser = routes.accesscontrol.authorize(users.ROLE_USER);
// public routes
router.post('/api/v1/cloudron/setup', json, routes.provision.setupTokenAuth, routes.provision.providerTokenAuth, routes.provision.setup); // only available until no-domain
@@ -113,16 +116,18 @@ function initializeExpressSync() {
router.post('/api/v1/cloudron/check_for_updates', json, token, authorizeAdmin, routes.cloudron.checkForUpdates);
router.get ('/api/v1/cloudron/reboot', token, authorizeAdmin, routes.cloudron.isRebootRequired);
router.post('/api/v1/cloudron/reboot', json, token, authorizeAdmin, routes.cloudron.reboot);
router.get ('/api/v1/cloudron/graphs', token, authorizeAdmin, routes.graphs.getGraphs);
router.get ('/api/v1/cloudron/graphs', token, authorizeAdmin, routes.cloudron.getSystemGraphs);
router.get ('/api/v1/cloudron/disks', token, authorizeAdmin, routes.cloudron.getDisks);
router.get ('/api/v1/cloudron/disk_usage', token, authorizeAdmin, routes.cloudron.getDiskUsage);
router.post('/api/v1/cloudron/disk_usage', token, authorizeAdmin, routes.cloudron.updateDiskUsage);
router.get ('/api/v1/cloudron/memory', token, authorizeAdmin, routes.cloudron.getMemory);
router.get ('/api/v1/cloudron/logs/:unit', token, authorizeAdmin, routes.cloudron.getLogs);
router.get ('/api/v1/cloudron/logstream/:unit', token, authorizeAdmin, routes.cloudron.getLogStream);
router.get ('/api/v1/cloudron/eventlog', token, authorizeAdmin, routes.eventlog.list);
router.get ('/api/v1/cloudron/eventlog/:eventId', token, authorizeAdmin, routes.eventlog.get);
router.post('/api/v1/cloudron/sync_external_ldap', json, token, authorizeAdmin, routes.cloudron.syncExternalLdap);
router.get ('/api/v1/cloudron/server_ipv4', token, authorizeAdmin, routes.cloudron.getServerIpv4);
router.get ('/api/v1/cloudron/server_ipv6', token, authorizeAdmin, routes.cloudron.getServerIpv6);
router.get ('/api/v1/cloudron/server_ipv4', token, authorizeAdmin, routes.cloudron.getServerIpv4);
router.get ('/api/v1/cloudron/server_ipv6', token, authorizeAdmin, routes.cloudron.getServerIpv6);
// task routes
router.get ('/api/v1/tasks', token, authorizeAdmin, routes.tasks.list);
@@ -144,31 +149,31 @@ function initializeExpressSync() {
router.post('/api/v1/backups/:backupId', json, token, authorizeAdmin, routes.backups.update);
// config route (for dashboard). can return some private configuration unlike status
router.get ('/api/v1/config', token, routes.cloudron.getConfig);
router.get ('/api/v1/config', token, authorizeUser, routes.cloudron.getConfig);
// working off the user behind the provided token
router.get ('/api/v1/profile', token, routes.profile.get);
router.post('/api/v1/profile', json, token, routes.profile.authorize, routes.profile.update);
router.get ('/api/v1/profile/avatar/:identifier', routes.profile.getAvatar); // this is not scoped so it can used directly in img tag
router.post('/api/v1/profile/avatar', json, token, (req, res, next) => { return typeof req.body.avatar === 'string' ? next() : multipart(req, res, next); }, routes.profile.setAvatar); // avatar is not exposed in LDAP. so it's personal and not locked
router.get ('/api/v1/profile/backgroundImage', token, routes.profile.getBackgroundImage);
router.post('/api/v1/profile/backgroundImage', token, multipart, routes.profile.setBackgroundImage); // backgroundImage is not exposed in LDAP. so it's personal and not locked
router.post('/api/v1/profile/password', json, token, routes.users.verifyPassword, routes.profile.setPassword);
router.post('/api/v1/profile/twofactorauthentication_secret', json, token, routes.profile.setTwoFactorAuthenticationSecret);
router.post('/api/v1/profile/twofactorauthentication_enable', json, token, routes.profile.enableTwoFactorAuthentication);
router.post('/api/v1/profile/twofactorauthentication_disable', json, token, routes.users.verifyPassword, routes.profile.disableTwoFactorAuthentication);
router.get ('/api/v1/profile', token, authorizeUser, routes.profile.get);
router.post('/api/v1/profile', json, token, authorizeUser, routes.profile.authorize, routes.profile.update);
router.get ('/api/v1/profile/avatar/:identifier', routes.profile.getAvatar); // this is not scoped so it can used directly in img tag
router.post('/api/v1/profile/avatar', json, token, authorizeUser, (req, res, next) => { return typeof req.body.avatar === 'string' ? next() : multipart(req, res, next); }, routes.profile.setAvatar); // avatar is not exposed in LDAP. so it's personal and not locked
router.get ('/api/v1/profile/backgroundImage', token, authorizeUser, routes.profile.getBackgroundImage);
router.post('/api/v1/profile/backgroundImage', token, authorizeUser, multipart, routes.profile.setBackgroundImage); // backgroundImage is not exposed in LDAP. so it's personal and not locked
router.post('/api/v1/profile/password', json, token, authorizeUser, routes.users.verifyPassword, routes.profile.setPassword);
router.post('/api/v1/profile/twofactorauthentication_secret', json, token, authorizeUser, routes.profile.setTwoFactorAuthenticationSecret);
router.post('/api/v1/profile/twofactorauthentication_enable', json, token, authorizeUser, routes.profile.enableTwoFactorAuthentication);
router.post('/api/v1/profile/twofactorauthentication_disable', json, token, authorizeUser, routes.users.verifyPassword, routes.profile.disableTwoFactorAuthentication);
// app password routes
router.get ('/api/v1/app_passwords', token, routes.appPasswords.list);
router.post('/api/v1/app_passwords', json, token, routes.appPasswords.add);
router.get ('/api/v1/app_passwords/:id', token, routes.appPasswords.get);
router.del ('/api/v1/app_passwords/:id', token, routes.appPasswords.del);
router.get ('/api/v1/app_passwords', token, authorizeUser, routes.appPasswords.list);
router.post('/api/v1/app_passwords', json, token, authorizeUser, routes.appPasswords.add);
router.get ('/api/v1/app_passwords/:id', token, authorizeUser, routes.appPasswords.get);
router.del ('/api/v1/app_passwords/:id', token, authorizeUser, routes.appPasswords.del);
// access tokens
router.get ('/api/v1/tokens', token, routes.tokens.list);
router.post('/api/v1/tokens', json, token, routes.tokens.add);
router.get ('/api/v1/tokens/:id', token, routes.tokens.verifyOwnership, routes.tokens.get);
router.del ('/api/v1/tokens/:id', token, routes.tokens.verifyOwnership, routes.tokens.del);
router.get ('/api/v1/tokens', token, authorizeUser, routes.tokens.list);
router.post('/api/v1/tokens', json, token, authorizeUser, routes.tokens.add);
router.get ('/api/v1/tokens/:id', token, authorizeUser, routes.tokens.verifyOwnership, routes.tokens.get);
router.del ('/api/v1/tokens/:id', token, authorizeUser, routes.tokens.verifyOwnership, routes.tokens.del);
// user routes
router.get ('/api/v1/users', token, authorizeUserManager, routes.users.list);
@@ -179,37 +184,37 @@ function initializeExpressSync() {
router.post('/api/v1/users/:userId/password', json, token, authorizeUserManager, routes.users.load, routes.users.setPassword);
router.post('/api/v1/users/:userId/ghost', json, token, authorizeAdmin, routes.users.load, routes.users.setGhost);
router.put ('/api/v1/users/:userId/groups', json, token, authorizeUserManager, routes.users.load, routes.users.setGroups);
router.post('/api/v1/users/:userId/twofactorauthentication_disable', json, token, authorizeUserManager, routes.users.load, routes.users.disableTwoFactorAuthentication);
router.get ('/api/v1/users/:userId/password_reset_link', json, token, authorizeUserManager, routes.users.load, routes.users.getPasswordResetLink);
router.post('/api/v1/users/:userId/send_password_reset_email', json, token, authorizeUserManager, routes.users.load, routes.users.sendPasswordResetEmail);
router.get ('/api/v1/users/:userId/invite_link', json, token, authorizeUserManager, routes.users.load, routes.users.getInviteLink);
router.post('/api/v1/users/:userId/send_invite_email', json, token, authorizeUserManager, routes.users.load, routes.users.sendInviteEmail);
router.post('/api/v1/users/:userId/make_local', json, token, authorizeUserManager, routes.users.load, routes.users.makeLocal);
router.get ('/api/v1/users/:userId/password_reset_link', json, token, authorizeUserManager, routes.users.load, routes.users.getPasswordResetLink);
router.post('/api/v1/users/:userId/send_password_reset_email', json, token, authorizeUserManager, routes.users.load, routes.users.sendPasswordResetEmail);
router.get ('/api/v1/users/:userId/invite_link', json, token, authorizeUserManager, routes.users.load, routes.users.getInviteLink);
router.post('/api/v1/users/:userId/send_invite_email', json, token, authorizeUserManager, routes.users.load, routes.users.sendInviteEmail);
router.post('/api/v1/users/:userId/twofactorauthentication_disable', json, token, authorizeUserManager, routes.users.load, routes.users.disableTwoFactorAuthentication);
// Group management
router.get ('/api/v1/groups', token, authorizeUserManager, routes.groups.list);
router.post('/api/v1/groups', json, token, authorizeUserManager, routes.groups.add);
router.get ('/api/v1/groups/:groupId', token, authorizeUserManager, routes.groups.get);
router.put ('/api/v1/groups/:groupId/members', json, token, authorizeUserManager, routes.groups.updateMembers);
router.put ('/api/v1/groups/:groupId/members', json, token, authorizeUserManager, routes.groups.setMembers);
router.post('/api/v1/groups/:groupId', json, token, authorizeUserManager, routes.groups.update);
router.del ('/api/v1/groups/:groupId', token, authorizeUserManager, routes.groups.remove);
// appstore and subscription routes
router.post('/api/v1/appstore/register_cloudron', json, token, authorizeOwner, routes.appstore.registerCloudron);
router.get ('/api/v1/appstore/web_token', json, token, authorizeOwner, routes.appstore.getWebToken);
router.get ('/api/v1/appstore/subscription', token, routes.appstore.getSubscription); // for all users
router.get ('/api/v1/appstore/subscription', token, authorizeUser, routes.appstore.getSubscription); // for all users
router.get ('/api/v1/appstore/apps', token, authorizeAdmin, routes.appstore.getApps);
router.get ('/api/v1/appstore/apps/:appstoreId', token, authorizeAdmin, routes.appstore.getApp);
router.get ('/api/v1/appstore/apps/:appstoreId/versions/:versionId', token, authorizeAdmin, routes.appstore.getAppVersion);
// app routes
router.post('/api/v1/apps/install', json, token, authorizeAdmin, routes.apps.install);
router.get ('/api/v1/apps', token, routes.apps.listByUser);
router.post('/api/v1/apps/install', json, token, authorizeAdmin, routes.apps.install);
router.get ('/api/v1/apps', token, authorizeUser, routes.apps.listByUser);
router.get ('/api/v1/apps/:id', token, routes.apps.load, authorizeOperator, routes.apps.getApp);
router.get ('/api/v1/apps/:id/icon', token, routes.apps.load, routes.apps.getAppIcon);
router.post('/api/v1/apps/:id/uninstall', json, token, authorizeAdmin, routes.apps.load, routes.apps.uninstall);
router.post('/api/v1/apps/:id/configure/access_restriction', json, token, authorizeAdmin, routes.apps.load, routes.apps.setAccessRestriction);
router.post('/api/v1/apps/:id/configure/operators', json, token, authorizeAdmin, routes.apps.load, routes.apps.setOperators);
router.get ('/api/v1/apps/:id/icon', token, routes.apps.load, authorizeUser, routes.apps.getAppIcon);
router.post('/api/v1/apps/:id/uninstall', json, token, routes.apps.load, authorizeAdmin, routes.apps.uninstall);
router.post('/api/v1/apps/:id/configure/access_restriction', json, token, routes.apps.load, authorizeAdmin, routes.apps.setAccessRestriction);
router.post('/api/v1/apps/:id/configure/operators', json, token, routes.apps.load, authorizeAdmin, routes.apps.setOperators);
router.post('/api/v1/apps/:id/configure/label', json, token, routes.apps.load, authorizeOperator, routes.apps.setLabel);
router.post('/api/v1/apps/:id/configure/tags', json, token, routes.apps.load, authorizeOperator, routes.apps.setTags);
router.post('/api/v1/apps/:id/configure/icon', json, token, routes.apps.load, authorizeOperator, routes.apps.setIcon);
@@ -227,6 +232,7 @@ function initializeExpressSync() {
router.post('/api/v1/apps/:id/configure/location', json, token, routes.apps.load, authorizeAdmin, routes.apps.setLocation);
router.post('/api/v1/apps/:id/configure/mounts', json, token, routes.apps.load, authorizeAdmin, routes.apps.setMounts);
router.post('/api/v1/apps/:id/configure/crontab', json, token, routes.apps.load, authorizeOperator, routes.apps.setCrontab);
router.post('/api/v1/apps/:id/configure/upstream_uri', json, token, routes.apps.load, authorizeOperator, routes.apps.setUpstreamUri);
router.post('/api/v1/apps/:id/repair', json, token, routes.apps.load, authorizeOperator, routes.apps.repair);
router.post('/api/v1/apps/:id/check_for_updates', json, token, routes.apps.load, authorizeOperator, routes.apps.checkForUpdates);
router.post('/api/v1/apps/:id/update', json, token, routes.apps.load, authorizeOperator, routes.apps.update);
@@ -244,7 +250,7 @@ function initializeExpressSync() {
router.get ('/api/v1/apps/:id/eventlog', token, routes.apps.load, authorizeOperator, routes.apps.listEventlog);
router.get ('/api/v1/apps/:id/limits', token, routes.apps.load, authorizeOperator, routes.apps.getLimits);
router.get ('/api/v1/apps/:id/task', token, routes.apps.load, authorizeOperator, routes.apps.getTask);
router.get ('/api/v1/apps/:id/graphs', token, routes.apps.load, authorizeOperator, routes.graphs.getGraphs); // TODO: restrict to app graphs
router.get ('/api/v1/apps/:id/graphs', token, routes.apps.load, authorizeOperator, routes.apps.getGraphs);
router.post('/api/v1/apps/:id/clone', json, token, routes.apps.load, authorizeAdmin, routes.apps.clone);
router.get ('/api/v1/apps/:id/download', token, routes.apps.load, authorizeOperator, routes.apps.downloadFile);
router.post('/api/v1/apps/:id/upload', json, token, multipart, routes.apps.load, authorizeOperator, routes.apps.uploadFile);
@@ -254,7 +260,15 @@ function initializeExpressSync() {
router.get ('/api/v1/apps/:id/exec/:execId', token, routes.apps.load, authorizeOperator, routes.apps.getExec);
// websocket cannot do bearer authentication
router.get ('/api/v1/apps/:id/exec/:execId/startws', token, routes.apps.load, routes.accesscontrol.authorizeOperator, routes.apps.startExecWebSocket);
router.get ('/api/v1/apps/:id/exec/:execId/startws', token, routes.apps.load, authorizeOperator, routes.apps.startExecWebSocket);
// app links in dashboard
router.get ('/api/v1/applinks', token, authorizeUser, routes.applinks.listByUser);
router.post('/api/v1/applinks', json, token, authorizeAdmin, routes.applinks.add);
router.get ('/api/v1/applinks/:id', token, authorizeAdmin, routes.applinks.get);
router.post('/api/v1/applinks/:id', json, token, authorizeAdmin, routes.applinks.update);
router.del ('/api/v1/applinks/:id', token, authorizeAdmin, routes.applinks.remove);
router.get ('/api/v1/applinks/:id/icon', token, authorizeUser, routes.applinks.getIcon);
// branding routes
router.get ('/api/v1/branding/:setting', token, authorizeOwner, routes.branding.get);
@@ -291,6 +305,8 @@ function initializeExpressSync() {
router.post('/api/v1/mailserver/mailbox_sharing', token, authorizeAdmin, routes.mailserver.proxy, routes.mailserver.restart);
router.get ('/api/v1/mailserver/usage', token, authorizeMailManager, routes.mailserver.proxy);
router.use ('/api/v1/mailserver/queue', token, authorizeAdmin, routes.mailserver.queueProxy);
router.get ('/api/v1/mail/:domain', token, authorizeMailManager, routes.mail.getDomain);
router.post('/api/v1/mail/:domain/enable', json, token, authorizeAdmin, routes.mail.setMailEnabled);
router.get ('/api/v1/mail/:domain/status', token, authorizeMailManager, routes.mail.getStatus);
@@ -314,16 +330,16 @@ function initializeExpressSync() {
router.del ('/api/v1/mail/:domain/lists/:name', token, authorizeMailManager, routes.mail.delList);
// support routes
router.post('/api/v1/support/ticket', json, token, authorizeAdmin, routes.support.canCreateTicket, routes.support.createTicket);
router.get ('/api/v1/support/remote_support', token, authorizeAdmin, routes.support.getRemoteSupport);
router.post('/api/v1/support/remote_support', json, token, authorizeAdmin, routes.support.canEnableRemoteSupport, routes.support.enableRemoteSupport);
router.post('/api/v1/support/ticket', json, token, authorizeOwner, routes.support.canCreateTicket, routes.support.createTicket);
router.get ('/api/v1/support/remote_support', token, authorizeOwner, routes.support.getRemoteSupport);
router.post('/api/v1/support/remote_support', json, token, authorizeOwner, routes.support.canEnableRemoteSupport, routes.support.enableRemoteSupport);
// domain routes
router.post('/api/v1/domains', json, token, authorizeAdmin, routes.domains.add);
router.get ('/api/v1/domains', token, routes.domains.list);
router.get ('/api/v1/domains', token, authorizeUser, routes.domains.list);
router.get ('/api/v1/domains/:domain', token, authorizeAdmin, routes.domains.get); // this is manage scope because it returns non-restricted fields
router.post('/api/v1/domains/:domain/config', json, token, authorizeAdmin, routes.domains.setConfig);
router.post('/api/v1/domains/:domain/wellknown', json, token, authorizeAdmin, routes.domains.setWellKnown);
router.post('/api/v1/domains/:domain/config', json, token, authorizeAdmin, routes.domains.setConfig);
router.post('/api/v1/domains/:domain/wellknown', json, token, authorizeAdmin, routes.domains.setWellKnown);
router.del ('/api/v1/domains/:domain', token, authorizeAdmin, routes.domains.del);
router.get ('/api/v1/domains/:domain/dns_check', token, authorizeAdmin, routes.domains.checkDnsRecords);
@@ -340,6 +356,7 @@ function initializeExpressSync() {
router.get ('/api/v1/services', token, authorizeAdmin, routes.services.list);
router.get ('/api/v1/services/:service', token, authorizeAdmin, routes.services.get);
router.post('/api/v1/services/:service', json, token, authorizeAdmin, routes.services.configure);
router.get ('/api/v1/services/:service/graphs', token, authorizeAdmin, routes.services.getGraphs);
router.get ('/api/v1/services/:service/logs', token, authorizeAdmin, routes.services.getLogs);
router.get ('/api/v1/services/:service/logstream', token, authorizeAdmin, routes.services.getLogStream);
router.post('/api/v1/services/:service/restart', json, token, authorizeAdmin, routes.services.restart);
+16 -7
View File
@@ -310,7 +310,7 @@ async function containerStatus(containerName, tokenEnvName) {
}
async function listServices() {
let serviceIds = Object.keys(SERVICES);
const serviceIds = Object.keys(SERVICES);
const result = await apps.list();
for (let app of result) {
@@ -502,7 +502,9 @@ async function rebuildService(id, auditSource) {
// this attempts to recreate the service docker container if they don't exist but platform infra version is unchanged
// passing an infra version of 'none' will not attempt to purge existing data
switch (id) {
const [name, instance] = id.split(':');
switch (name) {
case 'turn':
await startTurn({ version: 'none' });
break;
@@ -524,13 +526,18 @@ async function rebuildService(id, auditSource) {
case 'mail':
await mail.startMail({ version: 'none' });
break;
case 'redis': {
await shell.promises.exec('removeRedis', `docker rm -f redis-${instance} || true`);
const app = await apps.get(instance);
if (app) await setupRedis(app, app.manifest.addons.redis); // starts the container
break;
}
default:
// nothing to rebuild for now.
}
safe(applyMemoryLimit(id), { debug }); // do this in background. ok to fail
// TODO: missing redis container is not created
await eventlog.add(eventlog.ACTION_SERVICE_REBUILD, auditSource, { id });
}
@@ -1639,6 +1646,7 @@ async function startGraphite(existingInfra) {
const readOnly = !serviceConfig.recoveryMode ? '--read-only' : '';
const cmd = serviceConfig.recoveryMode ? '/bin/bash -c \'echo "Debug mode. Sleeping" && sleep infinity\'' : '';
// port 2003 is used by collectd
const runCmd = `docker run --restart=always -d --name="graphite" \
--hostname graphite \
--net cloudron \
@@ -1652,8 +1660,6 @@ async function startGraphite(existingInfra) {
--dns 172.18.0.1 \
--dns-search=. \
-p 127.0.0.1:2003:2003 \
-p 127.0.0.1:2004:2004 \
-p 127.0.0.1:8417:8000 \
-v "${paths.PLATFORM_DATA_DIR}/graphite:/var/lib/graphite" \
--label isCloudronManaged=true \
${readOnly} -v /tmp -v /run "${tag}" ${cmd}`;
@@ -1699,7 +1705,7 @@ async function startRedis(existingInfra) {
for (const app of allApps) {
if (!('redis' in app.manifest.addons)) continue; // app doesn't use the addon
const redisName = 'redis-' + app.id;
const redisName = `redis-${app.id}`;
if (upgrading) await backupRedis(app, {});
@@ -1876,7 +1882,10 @@ async function statusGraphite() {
if (error && error.reason === BoxError.NOT_FOUND) return { status: exports.SERVICE_STATUS_STOPPED };
if (error) throw error;
const [networkError, response] = await safe(superagent.get('http://127.0.0.1:8417/graphite-web/dashboard')
const ip = safe.query(container, 'NetworkSettings.Networks.cloudron.IPAddress', null);
if (!ip) throw new BoxError(BoxError.INACTIVE, 'Error getting IP of graphite service');
const [networkError, response] = await safe(superagent.get(`http://${ip}:8000/graphite-web/dashboard`)
.timeout(20000)
.ok(() => true));
+18 -22
View File
@@ -34,8 +34,8 @@ exports = module.exports = {
getExternalLdapConfig,
setExternalLdapConfig,
getUserDirectoryConfig,
setUserDirectoryConfig,
getDirectoryServerConfig,
setDirectoryServerConfig,
getRegistryConfig,
setRegistryConfig,
@@ -100,7 +100,7 @@ exports = module.exports = {
BACKUP_CONFIG_KEY: 'backup_config',
SERVICES_CONFIG_KEY: 'services_config',
EXTERNAL_LDAP_KEY: 'external_ldap_config',
USER_DIRECTORY_KEY: 'user_directory_config',
DIRECTORY_SERVER_KEY: 'user_directory_config',
REGISTRY_CONFIG_KEY: 'registry_config',
SYSINFO_CONFIG_KEY: 'sysinfo_config', // misnomer: ipv4 config
APPSTORE_LISTING_CONFIG_KEY: 'appstore_listing_config',
@@ -148,6 +148,7 @@ const assert = require('assert'),
CronJob = require('cron').CronJob,
database = require('./database.js'),
debug = require('debug')('box:settings'),
directoryServer = require('./directoryserver.js'),
docker = require('./docker.js'),
externalLdap = require('./externalldap.js'),
moment = require('moment-timezone'),
@@ -157,7 +158,6 @@ const assert = require('assert'),
sysinfo = require('./sysinfo.js'),
tokens = require('./tokens.js'),
translation = require('./translation.js'),
userdirectory = require('./userdirectory.js'),
users = require('./users.js'),
_ = require('underscore');
@@ -194,7 +194,7 @@ const gDefaults = (function () {
provider: 'noop',
autoCreate: false
};
result[exports.USER_DIRECTORY_KEY] = {
result[exports.DIRECTORY_SERVER_KEY] = {
enabled: false,
secret: '',
allowlist: '' // empty means allow all
@@ -455,7 +455,7 @@ async function setBackupConfig(backupConfig) {
}
// if any of these changes, we have to clear the cache
if ([ 'format', 'provider', 'prefix', 'bucket', 'region', 'endpoint', 'backupFolder', 'mountPoint', 'encryption' ].some(p => backupConfig[p] !== oldConfig[p])) {
if ([ 'format', 'provider', 'prefix', 'bucket', 'region', 'endpoint', 'backupFolder', 'mountPoint', 'encryption', 'encryptedFilenames' ].some(p => backupConfig[p] !== oldConfig[p])) {
debug('setBackupConfig: clearing backup cache');
backups.cleanupCacheFilesSync();
}
@@ -468,8 +468,6 @@ async function setBackupConfig(backupConfig) {
}
notifyChange(exports.BACKUP_CONFIG_KEY, backupConfig);
await backups.configureCollectd(backupConfig);
}
async function setBackupCredentials(credentials) {
@@ -487,8 +485,6 @@ async function setBackupCredentials(credentials) {
await set(exports.BACKUP_CONFIG_KEY, JSON.stringify(backupConfig));
notifyChange(exports.BACKUP_CONFIG_KEY, backupConfig);
await backups.configureCollectd(backupConfig);
}
async function getServicesConfig() {
@@ -528,29 +524,29 @@ async function setExternalLdapConfig(externalLdapConfig) {
notifyChange(exports.EXTERNAL_LDAP_KEY, externalLdapConfig);
}
async function getUserDirectoryConfig() {
const value = await get(exports.USER_DIRECTORY_KEY);
if (value === null) return gDefaults[exports.USER_DIRECTORY_KEY];
async function getDirectoryServerConfig() {
const value = await get(exports.DIRECTORY_SERVER_KEY);
if (value === null) return gDefaults[exports.DIRECTORY_SERVER_KEY];
return JSON.parse(value);
}
async function setUserDirectoryConfig(userDirectoryConfig) {
assert.strictEqual(typeof userDirectoryConfig, 'object');
async function setDirectoryServerConfig(directoryServerConfig) {
assert.strictEqual(typeof directoryServerConfig, 'object');
if (isDemo()) throw new BoxError(BoxError.BAD_FIELD, 'Not allowed in demo mode');
const config = {
enabled: userDirectoryConfig.enabled,
secret: userDirectoryConfig.secret,
enabled: directoryServerConfig.enabled,
secret: directoryServerConfig.secret,
// if list is empty, we allow all IPs
allowlist: userDirectoryConfig.allowlist || ''
allowlist: directoryServerConfig.allowlist || ''
};
await userdirectory.validateConfig(config);
await set(exports.USER_DIRECTORY_KEY, JSON.stringify(config));
await userdirectory.applyConfig(config);
await directoryServer.validateConfig(config);
await set(exports.DIRECTORY_SERVER_KEY, JSON.stringify(config));
await directoryServer.applyConfig(config);
notifyChange(exports.USER_DIRECTORY_KEY, config);
notifyChange(exports.DIRECTORY_SERVER_KEY, config);
}
async function getRegistryConfig() {
+1
View File
@@ -22,6 +22,7 @@ function api(provider) {
case 'wasabi': return require('./storage/s3.js');
case 'scaleway-objectstorage': return require('./storage/s3.js');
case 'backblaze-b2': return require('./storage/s3.js');
case 'cloudflare-r2': return require('./storage/s3.js');
case 'linode-objectstorage': return require('./storage/s3.js');
case 'ovh-objectstorage': return require('./storage/s3.js');
case 'ionos-objectstorage': return require('./storage/s3.js');
+16 -33
View File
@@ -1,8 +1,9 @@
'use strict';
exports = module.exports = {
getRootPath,
checkPreconditions,
getBackupRootPath,
getBackupProviderStatus,
getAvailableSize,
upload,
download,
@@ -33,7 +34,6 @@ const PROVIDER_EXT4 = 'ext4';
const assert = require('assert'),
BoxError = require('../boxerror.js'),
constants = require('../constants.js'),
DataLayout = require('../datalayout.js'),
debug = require('debug')('box:storage/filesystem'),
df = require('@sindresorhus/df'),
fs = require('fs'),
@@ -45,7 +45,7 @@ const assert = require('assert'),
shell = require('../shell.js');
// storage api
function getRootPath(apiConfig) {
function getBackupRootPath(apiConfig) {
assert.strictEqual(typeof apiConfig, 'object');
switch (apiConfig.provider) {
@@ -62,43 +62,26 @@ function getRootPath(apiConfig) {
}
}
// binary units (non SI) 1024 based
function prettyBytes(bytes) {
assert.strictEqual(typeof bytes, 'number');
async function getBackupProviderStatus(apiConfig) {
assert.strictEqual(typeof apiConfig, 'object');
const i = Math.floor(Math.log(bytes) / Math.log(1024)),
sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
// Check filesystem is mounted so we don't write into the actual folder on disk
if (mounts.isManagedProvider(apiConfig.provider) || apiConfig.provider === 'mountpoint') {
const hostPath = mounts.isManagedProvider(apiConfig.provider) ? paths.MANAGED_BACKUP_MOUNT_DIR : apiConfig.mountPoint;
return await mounts.getStatus(apiConfig.provider, hostPath); // { state, message }
}
return (bytes / Math.pow(1024, i)).toFixed(2) * 1 + '' + sizes[i];
return await mounts.getStatus(apiConfig.provider, apiConfig.backupFolder);
}
// the du call in the function below requires root
async function checkPreconditions(apiConfig, dataLayout) {
async function getAvailableSize(apiConfig) {
assert.strictEqual(typeof apiConfig, 'object');
assert(dataLayout instanceof DataLayout, 'dataLayout must be a DataLayout');
let used = 0;
for (let localPath of dataLayout.localPaths()) {
debug(`checkPreconditions: getting disk usage of ${localPath}`);
let result = safe.child_process.execSync(`du -Dsb ${localPath}`, { encoding: 'utf8' });
if (!result) throw new BoxError(BoxError.FS_ERROR, `du error: ${safe.error.message}`);
used += parseInt(result, 10);
}
debug(`checkPreconditions: ${used} bytes`);
const [error, result] = await safe(df.file(getRootPath(apiConfig)));
const [error, dfResult] = await safe(df.file(getBackupRootPath(apiConfig)));
if (error) throw new BoxError(BoxError.FS_ERROR, `Error when checking for disk space: ${error.message}`);
// Check filesystem is mounted so we don't write into the actual folder on disk
if (apiConfig.provider === PROVIDER_SSHFS || apiConfig.provider === PROVIDER_CIFS || apiConfig.provider === PROVIDER_NFS || apiConfig.provider === PROVIDER_EXT4 || apiConfig.provider === PROVIDER_XFS) {
if (result.mountpoint !== paths.MANAGED_BACKUP_MOUNT_DIR) throw new BoxError(BoxError.FS_ERROR, 'Backup target is not mounted');
} else if (apiConfig.provider === PROVIDER_MOUNTPOINT) {
if (result.mountpoint === '/') throw new BoxError(BoxError.FS_ERROR, `${apiConfig.backupFolder} is not mounted`);
}
const needed = 0.6 * used + (1024 * 1024 * 1024); // check if there is atleast 1GB left afterwards. aim for 60% because rsync/tgz won't need full 100%
if (result.available <= needed) throw new BoxError(BoxError.FS_ERROR, `Not enough disk space for backup. Needed: ${prettyBytes(needed)} Available: ${prettyBytes(result.available)}`);
return dfResult.available;
}
function hasChownSupportSync(apiConfig) {
@@ -308,7 +291,7 @@ async function testConfig(apiConfig) {
if (!safe.child_process.execSync(`mountpoint -q -- ${apiConfig.mountPoint}`)) throw new BoxError(BoxError.BAD_FIELD, `${apiConfig.mountPoint} is not mounted`);
}
const basePath = getRootPath(apiConfig);
const basePath = getBackupRootPath(apiConfig);
const field = apiConfig.provider === PROVIDER_FILESYSTEM ? 'backupFolder' : 'mountPoint';
if (!safe.fs.mkdirSync(path.join(basePath, 'snapshot'), { recursive: true }) && safe.error.code !== 'EEXIST') {
+13 -6
View File
@@ -1,8 +1,9 @@
'use strict';
exports = module.exports = {
getRootPath,
checkPreconditions,
getBackupRootPath,
getBackupProviderStatus,
getAvailableSize,
upload,
exists,
@@ -29,7 +30,6 @@ const assert = require('assert'),
async = require('async'),
BoxError = require('../boxerror.js'),
constants = require('../constants.js'),
DataLayout = require('../datalayout.js'),
debug = require('debug')('box:storage/gcs'),
PassThrough = require('stream').PassThrough,
path = require('path'),
@@ -66,15 +66,22 @@ function getBucket(apiConfig) {
}
// storage api
function getRootPath(apiConfig) {
function getBackupRootPath(apiConfig) {
assert.strictEqual(typeof apiConfig, 'object');
return apiConfig.prefix;
}
async function checkPreconditions(apiConfig, dataLayout) {
async function getBackupProviderStatus(apiConfig) {
assert.strictEqual(typeof apiConfig, 'object');
assert(dataLayout instanceof DataLayout, 'dataLayout must be a DataLayout');
return { state: 'active' };
}
async function getAvailableSize(apiConfig) {
assert.strictEqual(typeof apiConfig, 'object');
return Number.POSITIVE_INFINITY;
}
function upload(apiConfig, backupFilePath, sourceStream, callback) {
+14 -7
View File
@@ -11,8 +11,9 @@
// for the other API calls we leave it to the backend to retry. this allows
// them to tune the concurrency based on failures/rate limits accordingly
exports = module.exports = {
getRootPath,
checkPreconditions,
getBackupRootPath,
getBackupProviderStatus,
getAvailableSize,
upload,
@@ -34,8 +35,7 @@ exports = module.exports = {
};
const assert = require('assert'),
BoxError = require('../boxerror.js'),
DataLayout = require('../datalayout.js');
BoxError = require('../boxerror.js');
function removePrivateFields(apiConfig) {
// in-place removal of tokens and api keys with constants.SECRET_PLACEHOLDER
@@ -47,16 +47,23 @@ function injectPrivateFields(newConfig, currentConfig) {
// in-place injection of tokens and api keys which came in with constants.SECRET_PLACEHOLDER
}
function getRootPath(apiConfig) {
function getBackupRootPath(apiConfig) {
assert.strictEqual(typeof apiConfig, 'object');
// Result: path at the backup storage
return '/';
}
async function checkPreconditions(apiConfig, dataLayout) {
async function getBackupProviderStatus(apiConfig) {
assert.strictEqual(typeof apiConfig, 'object');
assert(dataLayout instanceof DataLayout, 'dataLayout must be a DataLayout');
return { state: 'active' };
}
async function getAvailableSize(apiConfig) {
assert.strictEqual(typeof apiConfig, 'object');
return Number.POSITIVE_INFINITY;
}
function upload(apiConfig, backupFilePath, sourceStream, callback) {
+13 -6
View File
@@ -1,8 +1,9 @@
'use strict';
exports = module.exports = {
getRootPath,
checkPreconditions,
getBackupRootPath,
getBackupProviderStatus,
getAvailableSize,
upload,
exists,
@@ -23,17 +24,23 @@ exports = module.exports = {
const assert = require('assert'),
BoxError = require('../boxerror.js'),
DataLayout = require('../datalayout.js'),
debug = require('debug')('box:storage/noop');
function getRootPath(apiConfig) {
function getBackupRootPath(apiConfig) {
assert.strictEqual(typeof apiConfig, 'object');
return '';
}
async function checkPreconditions(apiConfig, dataLayout) {
async function getBackupProviderStatus(apiConfig) {
assert.strictEqual(typeof apiConfig, 'object');
assert(dataLayout instanceof DataLayout, 'dataLayout must be a DataLayout');
return { state: 'active' };
}
async function getAvailableSize(apiConfig) {
assert.strictEqual(typeof apiConfig, 'object');
return Number.POSITIVE_INFINITY;
}
function upload(apiConfig, backupFilePath, sourceStream, callback) {
+13 -6
View File
@@ -1,8 +1,9 @@
'use strict';
exports = module.exports = {
getRootPath,
checkPreconditions,
getBackupRootPath,
getBackupProviderStatus,
getAvailableSize,
upload,
exists,
@@ -31,7 +32,6 @@ const assert = require('assert'),
AwsSdk = require('aws-sdk'),
BoxError = require('../boxerror.js'),
constants = require('../constants.js'),
DataLayout = require('../datalayout.js'),
debug = require('debug')('box:storage/s3'),
https = require('https'),
path = require('path'),
@@ -92,15 +92,22 @@ function getS3Config(apiConfig) {
}
// storage api
function getRootPath(apiConfig) {
function getBackupRootPath(apiConfig) {
assert.strictEqual(typeof apiConfig, 'object');
return apiConfig.prefix;
}
async function checkPreconditions(apiConfig, dataLayout) {
async function getBackupProviderStatus(apiConfig) {
assert.strictEqual(typeof apiConfig, 'object');
assert(dataLayout instanceof DataLayout, 'dataLayout must be a DataLayout');
return { state: 'active' };
}
async function getAvailableSize(apiConfig) {
assert.strictEqual(typeof apiConfig, 'object');
return Number.POSITIVE_INFINITY;
}
function upload(apiConfig, backupFilePath, sourceStream, callback) {
+106 -74
View File
@@ -4,7 +4,9 @@ exports = module.exports = {
getDisks,
checkDiskSpace,
getMemory,
getMemoryAllocation
getMemoryAllocation,
getDiskUsage,
updateDiskUsage
};
const apps = require('./apps.js'),
@@ -15,87 +17,84 @@ const apps = require('./apps.js'),
docker = require('./docker.js'),
notifications = require('./notifications.js'),
os = require('os'),
path = require('path'),
paths = require('./paths.js'),
safe = require('safetydance'),
settings = require('./settings.js'),
shell = require('./shell.js'),
volumes = require('./volumes.js');
async function getVolumeDisks(appsDataDisk) {
assert.strictEqual(typeof appsDataDisk, 'string');
const DU_CMD = path.join(__dirname, 'scripts/du.sh');
let volumeDisks = {};
const allVolumes = await volumes.list();
async function du(file) {
assert.strictEqual(typeof file, 'string');
for (const volume of allVolumes) {
const [error, result] = await safe(df(volume.hostPath));
volumeDisks[volume.id] = error ? appsDataDisk : result.filesystem; // ignore any errors
}
const [error, stdoutResult] = await safe(shell.promises.sudo('system', [ DU_CMD, file ], {}));
if (error) throw new BoxError(BoxError.FS_ERROR, error);
return volumeDisks;
}
async function getAppDisks(appsDataDisk) {
assert.strictEqual(typeof appsDataDisk, 'string');
let appDisks = {};
const allApps = await apps.list();
for (const app of allApps) {
if (!app.storageVolumeId) {
appDisks[app.id] = appsDataDisk;
} else {
const dataDir = await apps.getStorageDir(app);
const [error, result] = await safe(df.file(dataDir));
appDisks[app.id] = error ? appsDataDisk : result.filesystem; // ignore any errors
}
}
return appDisks;
}
async function getBackupsFilesystem() {
const backupConfig = await settings.getBackupConfig();
if (backupConfig.provider !== 'filesystem') return null;
const result = await df.file(backupConfig.backupFolder);
return result.filesystem;
return parseInt(stdoutResult.trim(), 10);
}
async function getDisks() {
const info = await docker.info();
let [dfError, dfEntries] = await safe(df());
if (dfError) throw new BoxError(BoxError.FS_ERROR, `Error running df: ${dfError.message}`);
let [error, allDisks] = await safe(df());
if (error) throw new BoxError(BoxError.FS_ERROR, error);
const disks = {}; // by file system
let rootDisk;
// filter by ext4 and then sort to make sure root disk is first
const ext4Disks = allDisks.filter((r) => r.type === 'ext4' || r.type === 'xfs').sort((a, b) => a.mountpoint.localeCompare(b.mountpoint));
const diskInfos = [];
for (const p of [ paths.BOX_DATA_DIR, paths.MAIL_DATA_DIR, paths.PLATFORM_DATA_DIR, paths.APPS_DATA_DIR, info.DockerRootDir ]) {
const [dfError, diskInfo] = await safe(df.file(p));
if (dfError) throw new BoxError(BoxError.FS_ERROR, dfError);
diskInfos.push(diskInfo);
for (const disk of dfEntries) {
if (disk.type !== 'ext4' && disk.type !== 'xfs') continue;
if (disk.mountpoint === '/') rootDisk = disk;
disks[disk.filesystem] = {
filesystem: disk.filesystem,
type: disk.type,
size: disk.size,
used: disk.used,
available: disk.available,
capacity: disk.capacity,
mountpoint: disk.mountpoint,
contents: [] // filled below
};
}
const backupsFilesystem = await getBackupsFilesystem();
const standardPaths = [
{ type: 'standard', id: 'platformdata', path: paths.PLATFORM_DATA_DIR },
{ type: 'standard', id: 'boxdata', path: paths.BOX_DATA_DIR },
{ type: 'standard', id: 'maildata', path: paths.MAIL_DATA_DIR },
];
const result = {
disks: ext4Disks, // root disk is first. { filesystem, type, size, used, available, capacity, mountpoint }
boxDataDisk: diskInfos[0].filesystem,
mailDataDisk: diskInfos[1].filesystem,
platformDataDisk: diskInfos[2].filesystem,
appsDataDisk: diskInfos[3].filesystem,
dockerDataDisk: diskInfos[4].filesystem,
backupsDisk: backupsFilesystem,
apps: {}, // filled below
volumes: {} // filled below
};
for (const stdPath of standardPaths) {
const [dfError, diskInfo] = await safe(df.file(stdPath.path));
if (dfError) throw new BoxError(BoxError.FS_ERROR, `Error getting std path: ${dfError.message}`);
disks[diskInfo.filesystem].contents.push(stdPath);
}
result.apps = await getAppDisks(result.appsDataDisk);
result.volumes = await getVolumeDisks(result.appsDataDisk);
const backupConfig = await settings.getBackupConfig();
if (backupConfig.provider === 'filesystem') {
const [, dfResult] = await safe(df.file(backupConfig.backupFolder));
disks[dfResult?.filesystem || rootDisk.filesystem].contents.push({ type: 'standard', id: 'cloudron-backup', path: backupConfig.backupFolder });
}
return result;
const [dockerError, dockerInfo] = await safe(docker.info());
if (!dockerError) {
const [, dfResult] = await safe(df.file(dockerInfo.DockerRootDir));
disks[dfResult?.filesystem || rootDisk.filesystem].contents.push({ type: 'standard', id: 'docker', path: dockerInfo.DockerRootDir });
}
for (const volume of await volumes.list()) {
const [, dfResult] = await safe(df(volume.hostPath));
disks[dfResult?.filesystem || rootDisk.filesystem].contents.push({ type: 'volume', id: volume.id, path: volume.hostPath });
}
for (const app of await apps.list()) {
if (!app.manifest.addons?.localstorage) continue;
const dataDir = await apps.getStorageDir(app);
const [, dfResult] = await safe(df.file(dataDir));
disks[dfResult?.filesystem || rootDisk.filesystem].contents.push({ type: 'app', id: app.id, path: dataDir });
}
return disks;
}
async function checkDiskSpace() {
@@ -105,18 +104,14 @@ async function checkDiskSpace() {
let markdownMessage = '';
disks.disks.forEach(function (entry) {
// ignore other filesystems but where box, app and platform data is
if (entry.filesystem !== disks.boxDataDisk
&& entry.filesystem !== disks.platformDataDisk
&& entry.filesystem !== disks.appsDataDisk
&& entry.filesystem !== disks.backupsDisk
&& entry.filesystem !== disks.dockerDataDisk) return false;
for (const filesystem of Object.keys(disks)) {
const disk = disks[filesystem];
if (disk.contents.length === 0) continue; // ignore if nothing interesting here
if (entry.available <= (1.25 * 1024 * 1024 * 1024)) { // 1.5G
markdownMessage += `* ${entry.filesystem} is at ${entry.capacity*100}% capacity.\n`;
if (disk.available <= (1.25 * 1024 * 1024 * 1024)) { // 1.5G
markdownMessage += `* ${disk.filesystem} is at ${disk.capacity*100}% capacity.\n`;
}
});
}
debug(`checkDiskSpace: disk space checked. out of space: ${markdownMessage || 'no'}`);
@@ -149,3 +144,40 @@ function getMemoryAllocation(limit) {
return Math.round(Math.round(limit * ratio) / 1048576) * 1048576; // nearest MB
}
async function getDiskUsage() {
return safe.JSON.parse(safe.fs.readFileSync(paths.DISK_USAGE_FILE, 'utf8'));
}
async function updateDiskUsage(progressCallback) {
assert.strictEqual(typeof progressCallback, 'function');
const disks = await getDisks();
const filesystems = Object.keys(disks);
const now = Date.now();
let percent = 1;
for (const filesystem of filesystems) {
const disk = disks[filesystem];
percent += (100/filesystems.length);
progressCallback({ percent, message: `Checking contents of ${filesystem}`});
for (const content of disk.contents) {
progressCallback({ message: `Checking du of ${JSON.stringify(content)}`});
if (content.id === 'docker') {
content.usage = (await docker.df()).LayersSize;
} else {
const [error, usage] = await safe(du(content.path));
if (error) progressCallback({ message: `du error: ${error.message}`}); // can happen if app is installing etc
content.usage = usage || 0;
}
progressCallback({ message: `du of ${JSON.stringify(content)}: ${content.usage}`});
}
}
if (!safe.fs.writeFileSync(paths.DISK_USAGE_FILE, JSON.stringify({ ts: now, disks }), 'utf8')) throw new BoxError(BoxError.FS_ERROR, `Could not write du cache file: ${safe.error.message}`);
return disks;
}

Some files were not shown because too many files have changed in this diff Show More