git-annex/Remote/Glacier.hs

318 lines
9 KiB
Haskell
Raw Normal View History

{- Amazon Glacier remotes.
-
- Copyright 2012 Joey Hess <id@joeyh.name>
-
- Licensed under the GNU GPL version 3 or higher.
-}
module Remote.Glacier (remote, jobList, checkSaneGlacierCommand) where
import qualified Data.Map as M
import qualified Data.Text as T
import qualified Data.ByteString.Lazy as L
import Common.Annex
import Types.Remote
import Types.Key
import qualified Git
import Config
import Config.Cost
import Remote.Helper.Special
2015-08-17 14:42:14 +00:00
import Remote.Helper.Messages
import qualified Remote.Helper.AWS as AWS
import Creds
import Utility.Metered
import qualified Annex
import Annex.UUID
import Utility.Env
type Vault = String
type Archive = FilePath
remote :: RemoteType
remote = RemoteType {
typename = "glacier",
enumerate = const (findSpecialRemotes "glacier"),
generate = gen,
setup = glacierSetup
}
gen :: Git.Repo -> UUID -> RemoteConfig -> RemoteGitConfig -> Annex (Maybe Remote)
gen r u c gc = new <$> remoteCost gc veryExpensiveRemoteCost
2012-11-30 04:55:59 +00:00
where
new cst = Just $ specialRemote' specialcfg c
(prepareStore this)
(prepareRetrieve this)
(simplyPrepare $ remove this)
(simplyPrepare $ checkKey this)
this
2012-11-30 04:55:59 +00:00
where
2014-12-16 19:26:13 +00:00
this = Remote
{ uuid = u
, cost = cst
, name = Git.repoDescribe r
, storeKey = storeKeyDummy
, retrieveKeyFile = retreiveKeyFileDummy
, retrieveKeyFileCheap = retrieveCheap this
, removeKey = removeKeyDummy
, checkPresent = checkPresentDummy
, checkPresentCheap = False
, whereisKey = Nothing
, remoteFsck = Nothing
, repairRepo = Nothing
, config = c
, repo = r
, gitconfig = gc
, localpath = Nothing
, readonly = False
, availability = GloballyAvailable
, remotetype = remote
, mkUnavailable = return Nothing
, getInfo = includeCredsInfo c (AWS.creds u) $
[ ("glacier vault", getVault c) ]
, claimUrl = Nothing
, checkUrl = Nothing
}
specialcfg = (specialRemoteCfg c)
-- Disabled until jobList gets support for chunks.
{ chunkConfig = NoChunks
}
glacierSetup :: Maybe UUID -> Maybe CredPair -> RemoteConfig -> Annex (RemoteConfig, UUID)
glacierSetup mu mcreds c = do
u <- maybe (liftIO genUUID) return mu
glacier, S3: Fix bug that caused embedded creds to not be encypted using the remote's key. encryptionSetup must be called before setRemoteCredPair. Otherwise, the RemoteConfig doesn't have the cipher in it, and so no cipher is used to encrypt the embedded creds. This is a security fix for non-shared encryption methods! For encryption=shared, there's no security problem, just an inconsistentency in whether the embedded creds are encrypted. This is very important to get right, so used some types to help ensure that setRemoteCredPair is only run after encryptionSetup. Note that the external special remote bypasses the type safety, since creds can be set after the initial remote config, if the external special remote program requests it. Also note that IA remotes never use encryption, so encryptionSetup is not run for them at all, and again the type safety is bypassed. This leaves two open questions: 1. What to do about S3 and glacier remotes that were set up using encryption=pubkey/hybrid with embedcreds? Such a git repo has a security hole embedded in it, and this needs to be communicated to the user. Is the changelog enough? 2. enableremote won't work in such a repo, because git-annex will try to decrypt the embedded creds, which are not encrypted, so fails. This needs to be dealt with, especially for ecryption=shared repos, which are not really broken, just inconsistently configured. Noticing that problem for encryption=shared is what led to commit fbdeeeed5fa276d94be587c8916d725eddcaf546, which tried to fix the problem by not decrypting the embedded creds. This commit was sponsored by Josh Taylor.
2014-09-18 21:07:17 +00:00
glacierSetup' (isJust mu) u mcreds c
glacierSetup' :: Bool -> UUID -> Maybe CredPair -> RemoteConfig -> Annex (RemoteConfig, UUID)
glacierSetup' enabling u mcreds c = do
(c', encsetup) <- encryptionSetup c
c'' <- setRemoteCredPair encsetup c' (AWS.creds u) mcreds
let fullconfig = c'' `M.union` defaults
unless enabling $
genVault fullconfig u
gitConfigSpecialRemote u fullconfig "glacier" "true"
return (fullconfig, u)
where
remotename = fromJust (M.lookup "name" c)
defvault = remotename ++ "-" ++ fromUUID u
defaults = M.fromList
[ ("datacenter", T.unpack $ AWS.defaultRegion AWS.Glacier)
, ("vault", defvault)
]
prepareStore :: Remote -> Preparer Storer
prepareStore r = checkPrepare nonEmpty (byteStorer $ store r)
nonEmpty :: Key -> Annex Bool
nonEmpty k
| keySize k == Just 0 = do
warning "Cannot store empty files in Glacier."
return False
| otherwise = return True
2012-11-25 17:42:28 +00:00
store :: Remote -> Key -> L.ByteString -> MeterUpdate -> Annex Bool
store r k b p = go =<< glacierEnv c u
2012-11-25 17:27:20 +00:00
where
2012-11-30 04:55:59 +00:00
c = config r
2012-11-25 17:27:20 +00:00
u = uuid r
params = glacierParams c
[ Param "archive"
, Param "upload"
, Param "--name", Param $ archive r k
2012-11-30 04:55:59 +00:00
, Param $ getVault $ config r
2012-11-25 17:27:20 +00:00
, Param "-"
]
2012-11-25 17:27:20 +00:00
go Nothing = return False
go (Just e) = do
let cmd = (proc "glacier" (toCommand params)) { env = Just e }
2012-11-25 17:27:20 +00:00
liftIO $ catchBoolIO $
withHandle StdinHandle createProcessSuccess cmd $ \h -> do
meteredWrite p h b
2012-11-25 17:27:20 +00:00
return True
prepareRetrieve :: Remote -> Preparer Retriever
prepareRetrieve = simplyPrepare . byteRetriever . retrieve
retrieve :: Remote -> Key -> (L.ByteString -> Annex Bool) -> Annex Bool
retrieve r k sink = go =<< glacierEnv c u
2012-11-25 17:42:28 +00:00
where
2012-11-30 04:55:59 +00:00
c = config r
2012-11-25 17:42:28 +00:00
u = uuid r
params = glacierParams c
[ Param "archive"
, Param "retrieve"
2012-11-25 17:42:28 +00:00
, Param "-o-"
2012-11-30 04:55:59 +00:00
, Param $ getVault $ config r
, Param $ archive r k
]
go Nothing = error "cannot retrieve from glacier"
2012-11-25 17:42:28 +00:00
go (Just e) = do
let cmd = (proc "glacier" (toCommand params))
{ env = Just e
, std_out = CreatePipe
}
(_, Just h, _, pid) <- liftIO $ createProcess cmd
-- Glacier cannot store empty files, so if the output is
-- empty, the content is not available yet.
ok <- ifM (liftIO $ hIsEOF h)
( return False
, sink =<< liftIO (L.hGetContents h)
)
liftIO $ hClose h
liftIO $ forceSuccessProcess cmd pid
unless ok $ do
showLongNote "Recommend you wait up to 4 hours, and then run this command again."
return ok
retrieveCheap :: Remote -> Key -> AssociatedFile -> FilePath -> Annex Bool
retrieveCheap _ _ _ _ = return False
remove :: Remote -> Remover
remove r k = glacierAction r
[ Param "archive"
, Param "delete"
2012-11-30 04:55:59 +00:00
, Param $ getVault $ config r
, Param $ archive r k
]
checkKey :: Remote -> CheckPresent
checkKey r k = do
2015-08-17 14:42:14 +00:00
showChecking r
2012-11-30 04:55:59 +00:00
go =<< glacierEnv (config r) (uuid r)
where
go Nothing = error "cannot check glacier"
2012-11-25 17:27:20 +00:00
go (Just e) = do
{- glacier checkpresent outputs the archive name to stdout if
- it's present. -}
s <- liftIO $ readProcessEnv "glacier" (toCommand params) (Just e)
let probablypresent = key2file k `elem` lines s
if probablypresent
then ifM (Annex.getFlag "trustglacier")
( return True, error untrusted )
else return False
params = glacierParams (config r)
[ Param "archive"
, Param "checkpresent"
2012-11-30 04:55:59 +00:00
, Param $ getVault $ config r
2012-11-21 23:35:28 +00:00
, Param "--quiet"
, Param $ archive r k
]
untrusted = unlines
[ "Glacier's inventory says it has a copy."
, "However, the inventory could be out of date, if it was recently removed."
, "(Use --trust-glacier if you're sure it's still in Glacier.)"
, ""
]
glacierAction :: Remote -> [CommandParam] -> Annex Bool
2013-09-26 03:19:01 +00:00
glacierAction r = runGlacier (config r) (uuid r)
runGlacier :: RemoteConfig -> UUID -> [CommandParam] -> Annex Bool
runGlacier c u params = go =<< glacierEnv c u
where
go Nothing = return False
2012-11-25 17:27:20 +00:00
go (Just e) = liftIO $
boolSystemEnv "glacier" (glacierParams c params) (Just e)
2012-11-25 17:27:20 +00:00
glacierParams :: RemoteConfig -> [CommandParam] -> [CommandParam]
glacierParams c params = datacenter:params
where
datacenter = Param $ "--region=" ++
fromMaybe (error "Missing datacenter configuration")
(M.lookup "datacenter" c)
glacierEnv :: RemoteConfig -> UUID -> Annex (Maybe [(String, String)])
glacierEnv c u = do
liftIO checkSaneGlacierCommand
go =<< getRemoteCredPairFor "glacier" c creds
where
go Nothing = return Nothing
go (Just (user, pass)) = do
2012-11-25 17:27:20 +00:00
e <- liftIO getEnvironment
return $ Just $ addEntries [(uk, user), (pk, pass)] e
creds = AWS.creds u
(uk, pk) = credPairEnvironment creds
getVault :: RemoteConfig -> Vault
getVault = fromMaybe (error "Missing vault configuration")
. M.lookup "vault"
archive :: Remote -> Key -> Archive
archive r k = fileprefix ++ key2file k
where
2012-11-30 04:55:59 +00:00
fileprefix = M.findWithDefault "" "fileprefix" $ config r
genVault :: RemoteConfig -> UUID -> Annex ()
genVault c u = unlessM (runGlacier c u params) $
error "Failed creating glacier vault."
where
params =
[ Param "vault"
, Param "create"
, Param $ getVault c
]
{- Partitions the input list of keys into ones which have
- glacier retieval jobs that have succeeded, or failed.
-
- A complication is that `glacier job list` will display the encrypted
- keys when the remote is encrypted.
-
- Dealing with encrypted chunked keys would be tricky. However, there
- seems to be no benefit to using chunking with glacier, so chunking is
- not supported.
-}
jobList :: Remote -> [Key] -> Annex ([Key], [Key])
2012-11-30 04:55:59 +00:00
jobList r keys = go =<< glacierEnv (config r) (uuid r)
where
params = [ Param "job", Param "list" ]
nada = ([], [])
2012-11-30 04:55:59 +00:00
myvault = getVault $ config r
go Nothing = return nada
go (Just e) = do
v <- liftIO $ catchMaybeIO $
readProcessEnv "glacier" (toCommand params) (Just e)
maybe (return nada) extract v
extract s = do
let result@(succeeded, failed) =
parse nada $ (map words . lines) s
if result == nada
then return nada
else do
enckeys <- forM keys $ \k ->
2014-07-27 00:21:36 +00:00
maybe k (\(_, enck) -> enck k)
<$> cipherKey (config r)
let keymap = M.fromList $ zip enckeys keys
2013-09-26 03:19:01 +00:00
let convert = mapMaybe (`M.lookup` keymap)
return (convert succeeded, convert failed)
parse c [] = c
parse c@(succeeded, failed) ((status:_date:vault:key:[]):rest)
| vault == myvault =
case file2key key of
Nothing -> parse c rest
Just k
| "a/d" `isPrefixOf` status ->
parse (k:succeeded, failed) rest
| "a/e" `isPrefixOf` status ->
parse (succeeded, k:failed) rest
| otherwise ->
parse c rest
parse c (_:rest) = parse c rest
-- boto's version of glacier exits 0 when given a parameter it doesn't
-- understand. See https://github.com/boto/boto/issues/2942
checkSaneGlacierCommand :: IO ()
checkSaneGlacierCommand =
whenM ((Nothing /=) <$> catchMaybeIO shouldfail) $
error wrongcmd
where
test = proc "glacier" ["--compatibility-test-git-annex"]
shouldfail = withQuietOutput createProcessSuccess test
wrongcmd = "The glacier program in PATH seems to be from boto, not glacier-cli. Cannot use this program."