/** Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.hadoop.mapreduce.security.token.delegation;

import java.security.PrivilegedExceptionAction;

import org.apache.hadoop.io.DataInputBuffer;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.MiniMRCluster;
import org.apache.hadoop.security.AccessControlException;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.security.token.SecretManager.InvalidToken;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;

@Disabled
public class TestDelegationToken {
  private MiniMRCluster cluster;
  private UserGroupInformation user1;
  private UserGroupInformation user2;
  
  @BeforeEach
  public void setup() throws Exception {
    user1 = UserGroupInformation.createUserForTesting("alice", 
                                                      new String[]{"users"});
    user2 = UserGroupInformation.createUserForTesting("bob", 
                                                      new String[]{"users"});
    cluster = new MiniMRCluster(0,0,1,"file:///",1);
  }
  
  @SuppressWarnings("deprecation")
  @Test
  public void testDelegationToken() throws Exception {
    
    final JobClient client;
    client = user1.doAs(new PrivilegedExceptionAction<JobClient>(){
      @Override
      public JobClient run() throws Exception {
        return new JobClient(cluster.createJobConf());
      }
    });
    
    final JobClient bobClient;
    bobClient = user2.doAs(new PrivilegedExceptionAction<JobClient>(){
      @Override
      public JobClient run() throws Exception {
        return new JobClient(cluster.createJobConf());
      }
    });
    
    final Token<DelegationTokenIdentifier> token = 
      client.getDelegationToken(new Text(user1.getUserName()));
    
    DataInputBuffer inBuf = new DataInputBuffer();
    byte[] bytes = token.getIdentifier();
    inBuf.reset(bytes, bytes.length);
    DelegationTokenIdentifier ident = new DelegationTokenIdentifier();
    ident.readFields(inBuf);
    
    assertEquals("alice", ident.getUser().getUserName());
    long createTime = ident.getIssueDate();
    long maxTime = ident.getMaxDate();
    long currentTime = System.currentTimeMillis();
    System.out.println("create time: " + createTime);
    System.out.println("current time: " + currentTime);
    System.out.println("max time: " + maxTime);
    assertTrue(createTime < currentTime, "createTime < current");
    assertTrue(currentTime < maxTime, "current < maxTime");

    // renew should work as user alice
    user1.doAs(new PrivilegedExceptionAction<Void>() {
      @Override
      public Void run() throws Exception {
        client.renewDelegationToken(token);
        client.renewDelegationToken(token);
        return null;
      }   
    });
    
    // bob should fail to renew
    user2.doAs(new PrivilegedExceptionAction<Void>() {
      @Override
      public Void run() throws Exception {
        try {
          bobClient.renewDelegationToken(token);
          fail("bob renew");
        } catch (AccessControlException ace) {
          // PASS
        }
        return null;
      }
    });
        
    // bob should fail to cancel
    user2.doAs(new PrivilegedExceptionAction<Void>() {
      @Override
      public Void run() throws Exception {
        try {
          bobClient.cancelDelegationToken(token);
          fail("bob cancel");
        } catch (AccessControlException ace) {
          // PASS
        }
        return null;
      }
    });
    
    // alice should be able to cancel but only cancel once
    user1.doAs(new PrivilegedExceptionAction<Void>() {
      @Override
      public Void run() throws Exception {
        client.cancelDelegationToken(token);
        try {
          client.cancelDelegationToken(token);
          fail("second alice cancel");
        } catch (InvalidToken it) {
          // PASS
        }
        return null;
      }   
    });
  }
}
